gpt4 book ai didi

c++ - 删除对象(具有不同类型)的引用时会发生什么?

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:14 24 4
gpt4 key购买 nike

我对引用在下面代码中的工作方式感到有点困惑。据我了解,b 只是 d1 的别名。那么 delete &bdelete d1 有什么区别呢?

b 是 Base 类型,但仍然是 f 类型的别名,那么它们有什么区别呢?

#include <iostream>

using namespace std;

class Base
{
public:
Base(){
cout << "Base Constructor Called\n";
}
~Base(){
cout << "Base Destructor called\n";
}
};

class Derived1: public Base
{
public:
Derived1(){
cout << "Derived constructor called\n";
}
~Derived1(){
cout << "Derived destructor called\n";
}
};

int main()
{
Derived1 *d1 = new Derived1();
Base &b = *d1;
delete &b;
}

最佳答案

它们按类型区分。

  • b 指的是 Base 类型的对象。

  • d1 指向 Derived1 类型的对象。

这些是相关但不同的类型。

您的对象是一个 Derived1,而不仅仅是一个 Base。这对 delete 很重要。使你的析构函数成为虚拟的,你就可以摆脱它,因为that's how polymorphism works .否则,你有未定义的行为,对你的程序没有意义。

关于c++ - 删除对象(具有不同类型)的引用时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515931/

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