gpt4 book ai didi

c++ - 为什么显式类型转换允许向上转换为私有(private)继承?

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

#include<iostream>
using namespace std;

class A {
public:
void f(){cout<<"A"<<endl;}
};

class B : private A {
public:
void f(){cout<<"B"<<endl;}
};

int main (){

由于 B 类私下继承 A 类,因此这种向上转换不应该起作用:

    A* a = new B;

但是显式类型转换是允许的。为什么?

    A* a1 = (A*)new B;
a1->f();
return 0;
}

最佳答案

类型转换

A* a1 = (A*)new B;

是对不可访问的基类的强制转换。

它只能表示为 C 风格的类型转换。如果在这种情况下可以使用 static_cast,则它等效于 static_cast 的作用,而不等效于 reinterpret_cast。特别是结果地址不一定与参数地址相同。

C++11 §5.4/4:

The same semantic restrictions and behaviors [as for a static_cast] apply [for a C style cast], with the exception that in performing a static_cast in the following situations the conversion is valid even if the base class is inaccessible:

— a pointer to an object of derived class type or an lvalue or rvalue of derived class type may be explicitly converted to a pointer or reference to an unambiguous base class type, respectively;

关于c++ - 为什么显式类型转换允许向上转换为私有(private)继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36327494/

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