使用dynamic_cast和构造函数时出错
error in using dynamic_cast and constructor
#include "stdafx.h"
#include <iostream>
using namespace std;
class myclass {
public:
int a;
myclass() : a(-1){};
};
class derivedclass : public myclass {
public:
int b;
derivedclass() : b(-2) {};
};
int main()
{
myclass* p= new myclass;
// derivedclass* pd = dynamic_cast<derivedclass*>(p);
derivedclass* pd = static_cast<derivedclass*>(p);
cout << pd->b << endl;
return 0;
}
我有两个问题。
dynamic_cast
不工作。因此需要在中添加一个虚拟函数myclass
- 为什么CCD_ 3不是CCD_构造函数
dynamic_cast
不工作有两个原因。
一个是,正如您所猜测的,dynamic_cast
需要虚拟函数才能工作,也就是说,基类型myclass
必须是多态的。
另一个原因也解决了你的第二个问题。在您的代码中,derivedclass
继承自myclass
。这意味着derivedclass
类型的任何对象也是myclass
类型的对象。这并不意味着任何类型为myclass
的对象也必然是derivedclass
的对象,正如您所假设的那样。
// creates a new instance of myclass, NOT an instance of derivedclass
myclass* p= new myclass;
// assuming myclass is polymorphic, returns a type-safe pointer to a derivedclass object
// if p is not such an object, returns nullptr, which is useful for error checking
derivedclass* pd1 = dynamic_cast<derivedclass*>(p);
// this is very unsafe! pd2 is now a 'wild' pointer to an object that doesn't exist
derivedclass* pd2 = static_cast<derivedclass*>(p);
// this is Undefined Behavior: there is no such `b` in memory at pd2, and that memory
// is not yours to read from
cout << pd2->b << endl;
pd->b
不是-2
的原因是derivedclass
的构造函数从未运行过。您从未创建过derivedclass
的对象。
dynamic_cast不工作。所以需要在derivedclass中添加一个虚拟函数吗?
是。您确实需要有一个虚拟函数才能使用动态强制转换。
此外,您必须检查动态强制转换是否会导致空指针。在这种情况下,它将导致null(如果存在虚拟函数(,因为p
不指向derivedclass
的实例。
为什么pd->b不是构造函数中初始化的-2?
行为未定义。从未建造过derivedclass
或其成员。
相关文章:
- 使用dynamic_cast和构造函数时出错
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 使用根/C++时出错:没有匹配的构造函数来初始化'TTree'
- 使用类的构造函数时出错
- 在 c++ 的构造函数中分配对象向量时出错
- 调用 cv::stereoBM 构造函数时出错
- 尝试从 C++ 中的构造函数从类继承时出错
- 尝试使用构造函数创建对象时出错
- 类中私有结构的构造函数出错
- 在构造函数中分配数组时出错
- 不可复制的对象、映射和shared_ptr:复制构造函数中出错
- 我的类默认构造函数出错
- 在另一个模板类构造函数中使用typdef模板时出错
- C++从构造函数返回值时出错
- 尝试在<int>构造函数中使用 vector 启动类时出错
- 在c++中初始化构造函数中的静态成员变量时出错
- 复制构造函数出错
- 结构初始化中的隐式复制构造函数出错
- 编译器错误消息错误:令牌之前的预期')' '*'。我的构造函数出错
- 调用构造函数出错