C++中的显式上行

C++中的显式上行,c++,inheritance,casting,C++,Inheritance,Casting,给出了A类、B类和C类的定义如下: 因为C既是A又是B 但我不能把[1]写成 而且我也不能把[2]写成 或 为什么要在[1]和[2]中明确向上投射? 为什么[3]没有被编译? 第一个是不可编译的,因为编译器不知道要调用什么构造函数,所以有3个构造函数 B(const A&) B(B&&) B(const B&) 编译器不能选择,因为C可以被强制转换为A和B 第二,因为没有赋值运算符C&运算符=常量B& 第三个无法编译,因为您无法将某些内容分配给临时变量和静态强制

给出了A类、B类和C类的定义如下:

因为C既是A又是B

但我不能把[1]写成

而且我也不能把[2]写成

为什么要在[1]和[2]中明确向上投射? 为什么[3]没有被编译?
第一个是不可编译的,因为编译器不知道要调用什么构造函数,所以有3个构造函数

B(const A&)
B(B&&)
B(const B&)
编译器不能选择,因为C可以被强制转换为A和B

第二,因为没有赋值运算符C&运算符=常量B&


第三个无法编译,因为您无法将某些内容分配给临时变量和静态强制转换*此创建类型为B的临时对象作为*此的副本。

只需编译有问题的代码并查看编译器的错误消息! 我用gcc为您做了这件事,结果如下:

[1] error: call of overloaded 'B(C&)' is ambiguous
       B(*this) // [1]
[2] error: no match for 'operator=' (operand types are 'C' and 'B')
      *this = B(); // [2]
应该是不言自明的

在大多数情况下,例如

A a = C();
B b = C();
A a = C();
B b = C();
请注意,这不是向上投射。那是一片。您正在将临时对象的一部分切片并分配给每个变量

也许你的意思是

 A const& a = C();  // need to use a reference to catch the C
 B const& b = C();  // Also because it is a temporary you need to use const

我不能,为什么不能?您收到了什么错误消息?FWIW,即使是正确的代码也不会编译,因为您没有初始化A基。@LightnessRacesinOrbit正确的代码在gcc和clang中都会编译,我问这个问题是因为我不清楚错误消息。如果我知道自己做错了什么,为什么还要问这个问题?
B(const A&)
B(B&&)
B(const B&)
[1] error: call of overloaded 'B(C&)' is ambiguous
       B(*this) // [1]
[2] error: no match for 'operator=' (operand types are 'C' and 'B')
      *this = B(); // [2]
A a = C();
B b = C();
 A const& a = C();  // need to use a reference to catch the C
 B const& b = C();  // Also because it is a temporary you need to use const