开发者

Is a class a namspace

开发者 https://www.devze.com 2023-01-17 09:40 出处:网络
the following code will help me illustate my question to you directly: #include<iostream> class foo {

the following code will help me illustate my question to you directly:

#include<iostream>

class foo {
  public:
  class bar {
    public:
      bar(int a) : m_a(a) {}
      void say() { std::cout << m_a << std::endl;}
   开发者_StackOverflow社区 private:
      int m_a;
  };
};


int main()
{
  foo::bar b(3);
  b.say();
}

as you see, to declare a object of class bar, we use the quite namespace like syntax "foo::bar", although actually bar is just an embebed class type in class foo. my question is does the scope of a class itself is a namespace in c++?


No, a class is not a namespace. A class does form a declarative region, though.

You use the same syntax (the :: operator) to refer to names declared at class scope as you do to refer to names declared at namespace scope.


The class is not a namespace, it is a scope. You already used this term yourself. Namespace is a scope. Class is a scope as well. The :: operator is a scope resolution operator. Scope, not namespace, is the fundamental term that can act as a "common denominator" in this case. Scope is the reason why you can use the :: operator with both classes and namespaces on the left-hand side.


Another interesting distinction between classes and namespaces is that a namespace can be declared over multiple files and in multiple parts, but a class cannot. For example, you could do:

File a.hpp:
    namespace Foo {
        int memberA;
    }

File b.hpp:
    namespace Foo {
        int memberB;
    }
    ...
    namespace Foo {
        int memberC;
    }


The scope of a class is not the same as the scope of a namespace. Classes can be templated, which affects the definitions in its scope. Classes can also have definitions that are only able to be used within that scope (private and protected).


The class name itself is not a namespace, although the scoping operator treats it as such, or almost as such anyways.

0

精彩评论

暂无评论...
验证码 换一张
取 消