私有继承:名称查找错误 [英] Private inheritance: name lookup error
问题描述
我有以下代码示例,不编译:
I have the following code example that doesn't compile:
#include <stdio.h>
namespace my
{
class base1
{ // line 6
};
class base2: private base1
{
};
class derived: private base2
{
public:
// The following function just wants to print a pointer, nothing else!
void print(base1* pointer) {printf("%p\n", pointer);}
};
}
gcc打印的错误是:
The error that gcc prints is:
test.cpp:6:错误:`class my :: base1'
无法访问
test.cpp:6: error: `class my::base1' is inaccessible
.cpp:17:错误:在此
上下文
test.cpp:17: error: within this context
现在,我可以猜到问题是: print
的声明,编译器会看到 base1
,并认为: base1
是 derived * this
的基类子对象,但是你不能访问它!虽然我打算 base1
应该只是一个类型名称。
Now, i can guess what the problem is: when looking at the declaration of print
, the compiler sees base1
and thinks: base1
is the base-class subobject of derived* this
, but you don't have access to it! While i intend that base1
should be just a type name.
如何在C ++标准中看到这个是一个正确的行为,而不是编译器中的一个错误(我确信它不是一个错误;所有编译器,我检查行为这样)?
How can i see in the C++ Standard that this is a correct behavior, and not a bug in the compiler (i am sure it's not a bug; all compilers i checked behaved so)?
我应该如何解决这个错误?所有以下修复都可以工作,但我应该选择哪一个?
How should i fix this error? All the following fixes work, but which one should i choose?
void print( class base1 * {}
void print(class base1* pointer) {}
void print( :: my :: base1 * pointer){}
void print(::my:: base1* pointer) {}
class base1;
void print(base1 * pointer){}
class base1; void print(base1* pointer) {}
b
$ b
编辑:
int main()
{
my::base1 object1;
my::derived object3;
object3.print(&object1);
}
推荐答案
为11.1。它建议使用:: my :: base1 *来解决这个问题:
The section you're looking for is 11.1. It suggests using ::my::base1* to work around this:
[注意:在派生类中,类名将在其声明的作用域中找到inject-class-name而不是基类的名称。 inject-class-name可能比声明的范围中的基类的名称更不可访问。 - end note]
[ 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
};
这篇关于私有继承:名称查找错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!