gpt4 book ai didi

c++ - 沮丧 : why: ‘A’ is an inaccessible base of ‘B’ ?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:13:44 27 4
gpt4 key购买 nike

与此错误消息的其他示例不同,我已经有一个指向 A 的指针并且想要检索实际的子类。

这种安排是一些 C++ 包装的 C 代码的一部分 A 是一些 POD C 结构(whatswhy 没有动态转换)而 test 是 C 中的一些回调调用 C++ 功能并检索应使用强制转换的正确对象。但是为了防止 C++ 用户代码弄乱 C-Baseclass,我希望继承 protected

MSVC 不会提示这个但 g++ 会提示!?从标准的角度来看,哪一个是正确的?为什么?

#include <iostream>

using namespace std;

// plain C structure
struct A{
int i;
};

// some C++ Wrapper class
struct B: protected A{
A* get() { return this; }
void print(){cout << i << endl;}
};



extern "C" {
// C callback that gives it this pointer
void test(A* io_self){
auto b2 = static_cast<B*>(io_self);
b2->print();
}
}

int main()
{
B b;
test(b.get());
return 0;
}

给出:

$g++ -std=c++11 -o main *.cpp
main.cpp: In function ‘void test(A*)’:
main.cpp:21:43: error: ‘A’ is an inaccessible base of ‘B’
auto b2 = static_cast<B*>(io_self);
^

最佳答案

来自 c++11 N3337 草案(有点旧,但它是我身边的那个)5.2.9/11 (static_cast):

A prvalue of type “pointer to cv1 B,” where B is a class type, can be converted to a prvalue of type “pointer to cv2 D,” where D is a class derived (Clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D.

在这种情况下,由于您使用了 protected 继承,因此没有从 BA 的有效标准转换,因此您的 static_cast 是非法的(g++ 诊断它是正确的)。

在这种情况下,由于您提供了一个围绕 C API 的 C++ 包装器,我认为最简单的方法是坚持公共(public)继承,并相信您的用户不会直接滥用 C API 如果他们已经有意识地选择使用您的 C++ API

关于c++ - 沮丧 : why: ‘A’ is an inaccessible base of ‘B’ ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47909196/

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