gpt4 book ai didi

c++ - 私有(private)继承 : name lookup error

转载 作者:IT老高 更新时间:2023-10-28 23:00:30 28 4
gpt4 key购买 nike

我有以下无法编译的代码示例:

#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 打印的错误是:

test.cpp:6: error: `class my::base1' is inaccessible

test.cpp:17: error: within this context

现在,我可以猜到问题出在哪里了:当查看 print 的声明时,编译器看到 base1 并认为:base1derived* this 的基类子对象,但您无权访问它!虽然我打算 base1 应该只是一个类型名称。

我如何在 C++ 标准中看到这是正确的行为,而不是编译器中的错误(我确信这不是错误;我检查过的所有编译器都是如此)?

我应该如何解决这个错误?以下所有修复都有效,但我应该选择哪一个?

void print(class base1* pointer) {}

void print(::my:: base1* pointer) {}

class base1; void print(base1* pointer) {}


编辑:

int main()
{
my::base1 object1;
my::derived object3;
object3.print(&object1);
}

最佳答案

您要查找的部分是 11.1。它建议使用::my::base1* 来解决这个问题:

[ 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
};

关于c++ - 私有(private)继承 : name lookup error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5634637/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com