If you compile the code below it fails, saying that class B is inaccessible where it is used as an argument to the member function func. Why is this?
Note: if D2 does not inherit from D1 then the error goes away, so somehow the inheritance from D2 makes B inaccessible.
namespace myns {
class B {};
}
using namespace myns;
class D1 : B {};
class D2 : D1 {
void func(B b) {}
};
Name lookup finds D2::D1::B
, not myns::B
. After name lookup, access check is performed, and discovers that D2::D1::B
is private.
The namespace is a red herring: the exact same outcome is observed if B
is defined in the global namespace.
You need to add the ::
operator. Lookup is finding the injected-class-name instead of the myns::B
.
class D2 : D1 {
void func(::B b) {}
};
11.1p5
5 [ Note: In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared. —end note ] [Example:
class A { };
class B : private A { };
class C : public B {
A *p; // error: injected-class-name A is inaccessible
::A *q; // OK
};
The default access specifier when inheriting a class/struct is "private", so your problem is this:
class D1 : B {};
class D2 : D1 {};
Add the keyword "public" and voila.
namespace myns {
class B {};
}
using namespace myns;
class D1 : public B {};
class D2 : public D1 {
void func(B b) {}
};
int main() {
D2 d();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.