使用dynamic_cast和构造函数时出错

error in using dynamic_cast and constructor

本文关键字:构造函数 出错 cast dynamic 使用      更新时间:2023-10-16
#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;
}

我有两个问题。

  1. dynamic_cast不工作。因此需要在中添加一个虚拟函数myclass
  2. 为什么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或其成员。