C ++ and entered base name

The following code does not compile in gcc:

namespace One{ class A{ }; }; namespace Two{ class A{ public: void what(){ cout << "Two::A says what!" << endl; } }; class B : public One::A{ public: B(){ A xx; xx.what(); } }; }; 

And he gives:

 gccbug.cpp: In constructor 'Two::B::B()': gccbug.cpp:23: error: 'class One::A' has no member named 'what' 

Now I have been told that this is the correct behavior (due to the entered base name One :: A making A refer to One :: A). However, this code compiles in C # (well, after changing a few things), so it looks like C ++.

I wonder why? Is there a specific purpose for injecting the base name "One :: A" as "A"?

+6
source share
3 answers

The only reason I can think of this is that in C ++, you most likely refer to the name of the base class in the list of constructor initializers, for example:

 namespace Two { /*...*/ class B : public One::A { public: B():A() { /*...*/ } }; } 

Of course, the target then differs from the target in your example, because you are actually declaring a local variable inside the constructor, whereas in my example A() refers to an object of type A , which is implied in the definition of class B due to inheritance.

However, the situation with my example is likely to happen, so I think they thought they did not require the namespace to be made explicit in this case. As a result, any reference to A without a namespace is interpreted as a reference to the base class, and not to any other class with the name A , even if it is in the same namespace as the declaration of B

+3
source

Is there a specific purpose for injecting the base name "One :: A" as "A"?

Yes. This can be done like this:

 namespace N { class A { A *a; }; } 

If there is no name entered, you should write N::A *a , which is not very nice.

Please note that this is due to the name entered, the following lines are allowed:

 A::A *a1; //ok A::A::A *a2; //ok A::A::A::A *a3; //ok A::A::A::A::A *a4; //ok //and so on 

online demo

+3
source

Rejecting A with One:: you added A from namespace one to the scope, so the compiler will look for name resolution there.

0
source

Source: https://habr.com/ru/post/909389/


All Articles