【发布时间】:2017-10-30 19:59:55
【问题描述】:
我编写了以下代码(这些类是在单独的 .h 文件中编写的):
class A
{
public:
A(){
cout << "This is the constructor of A!" << endl;
foo();
}
virtual ~A(){
cout << "Destroyed A type" << endl;
}
virtual void foo();
};
void A::foo()
{
cout << "foo()::A" << endl;
}
class B: public A
{
public:
B(){}
~B(){
cout << "Destroyed B type" << endl;
}
void foo();
};
void B::foo()
{
cout << "foo()::B" << endl;
}
还有以下主要功能:
int main()
{
A b = B();
A *bp = &b;
A &ra = b;
bp->foo();
ra.foo();
return 0;
}
当我运行它时,我得到以下输出:
This is the constructor of A!
foo()::A
Destroyed B type
Destroyed A type
foo()::A
foo()::A
Destroyed A type
我的问题是 - 为什么 B() 会立即被销毁? b 不应该指向它,成为 B 类型的对象吗?如何将 b 初始化为新的 B?也许我对Java感到困惑,我们会说b的静态类型是A,动态类型是B。这不是同样的情况吗?我很想了解这段代码背后的机制。
【问题讨论】:
-
也许我对 Java 感到困惑 - 你敢打赌!!
-
A b = B();这行代码创建了一个对象。而=右边的东西也创建了一个对象。 -
我强烈建议在 StackOverflow 中搜索“C++ 初始化构造函数析构函数”,因为已经有大量关于此主题的帖子。
-
试着向你的rubber duck解释这一行:
A b = B();。 -
能否在 B 构造函数中添加一些跟踪语句来查看 A b = B();创建一个A类型的类,调用一个B类型的类,然后销毁B,然后销毁A?
标签: c++ destructor