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

Discussion in 'C++' started by parmenides, Aug 21, 2013.

  1. parmenides

    parmenides Guest

    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.
    parmenides, Aug 21, 2013
    #1
    1. Advertising

  2. parmenides

    Stefan Ram Guest

    "parmenides" <> writes:
    >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++.
    Stefan Ram, Aug 21, 2013
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Èý¹â
    Replies:
    1
    Views:
    558
    William F. Robertson, Jr.
    Jul 29, 2003
  2. Mr. SweatyFinger
    Replies:
    2
    Views:
    1,762
    Smokey Grindel
    Dec 2, 2006
  3. robin liu
    Replies:
    3
    Views:
    812
    Robin Liu
    Apr 21, 2006
  4. eiji
    Replies:
    5
    Views:
    455
    Rolf Magnus
    Dec 6, 2005
  5. Peng Yu
    Replies:
    0
    Views:
    629
    Peng Yu
    Sep 14, 2008
Loading...

Share This Page