Why can not define a function in global namespace whit '::" ?

P

parmenides

Hi,

We can define a member function for a class like this:

class foo{
....
void mfunc(void);
};

void foo::mfunc(void)
{
... ...
}

Why we can not define a global function like this:

void ::func(void)
{
... ...
}

The former is modified by '::", while the latter can not. I wonder it seems
an odd strategy.
 
S

Stefan Ram

parmenides said:
Why we can not define a global function like this:

That's the way C++ was defined.

To define an identifier in the global namespace, one defines
it outside of any enclosing namespace, class, or function.

So, for example:

#include <iostream>
#include <ostream>

int f(){ return 71; }
int main(){ ::std::cout << ::f() << '\n'; }

»f« is in the global namespace.

To define f in the namespace ::a, one uses:

namespace a { int f ...}

, thus:

#include <iostream>
#include <ostream>

namespace a { int f(){ return 71; }}
int main(){ ::std::cout << ::a::f() << '\n'; }

. If one now substitutes "a"-->"", one gets:

#include <iostream>
#include <ostream>

namespace { int f(){ return 71; }}
int main(){ ::std::cout << ::::f() << '\n'; }

, but this is no valid C++ (even, if it would be, the fully
qualified name of »f« would be »::::f«, not »::f«).
»namespace { ...« already has another meaning in C++.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top