gpt4 book ai didi

具有多重继承的 C++ 类型转换

转载 作者:行者123 更新时间:2023-11-30 01:08:36 26 4
gpt4 key购买 nike

为什么 mother 对象能够在类型转换为 son 时调用 father 的函数?

这里 father 对象没有创建,那么 drive() 函数怎么会被调用。抱歉新手问题。

#include <iostream>
using namespace std;

#include <iostream>
using namespace std;
class father
{
public:
void drive(){cout<<"Driving";}
};
class mother
{
public:
void cook(){cout<<"Cooking";}
};
class son: public father, public mother
{

};
int main() {
// your code goes here
mother *m = new mother();
son* s = static_cast<son *>(m);
s->drive();
return 0;
}

最佳答案

您的代码具有未定义的行为,因为您试图通过类型 son 访问类型为 mother 的对象,这不是对象的动态类型。

更准确地说,[basic.lval]在标准中说:

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:56

  • the dynamic type of the object,
  • a cv-qualified version of the dynamic type of the object,
  • a type similar to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its elements or non-static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
  • a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
  • a char or unsigned char type.

引用 cppreference.com :

undefined behavior - there are no restrictions on the behavior of the program. Examples of undefined behavior are memory accesses outside of array bounds, signed integer overflow, null pointer dereference, modification of the same scalar more than once in an expression without sequence points, access to an object through a pointer of a different type, etc. Compilers are not required to diagnose undefined behavior (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful.

关于具有多重继承的 C++ 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42134181/

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