【发布时间】:2012-01-13 19:33:53
【问题描述】:
鉴于此代码:
#include <iostream>
using namespace std;
class Foo {
public:
Foo () { c = 'a'; cout << "Foo()" << endl; }
Foo (char ch) { c = ch; cout << "Foo(char)" << endl; }
~Foo () { cout << "~Foo()" << endl; }
private:
char c;
};
class Bar : public Foo {
public:
Bar () { cout << "Bar()" << endl; }
Bar (char ch) : Foo(ch) { cout << "Bar(char)" << endl; }
~Bar () { cout << "~Bar()" << endl; }
};
Foo f1; static Bar b1;
int main()
{
Bar b2;
{
static Foo f2('c');
Foo f3;
Bar b3 ('d');
}
return 0;
}
(您可以直接将其粘贴到编译器中)
我预期的示例输出的 first 部分是正确的:
Foo()
Foo()
Bar()
Foo()
Bar()
Foo(char)
Foo()
Foo(char)
Bar(char)
~Bar()
~Foo
~Foo()
~Bar()
~Foo()
~Foo()
但我得到两个静态对象static Bar b1; 和static Foo f2('c'); 的析构函数输出错误。
最后一部分的正确答案是:
~Bar()
~Foo()
~Foo()
我明白了:
~Foo()
~Bar()
~Foo()
这是我的推理:
我了解所有本地对象都在静态对象之前被破坏。在剩下的两个静态对象static Bar b1; 和static Foo f2('c'); 中,static Foo f2('c'); 出现在last,所以它被first 销毁,因为析构函数的调用顺序与它们的相反。创作。
但static Foo f2('c'); 不会首先被破坏,static Bar b1; 是。为什么?
【问题讨论】:
-
你应该添加一个成员变量来区分不同的对象。
-
仅供参考:我得到了你在使用 g++ 4.6.1 时所期望得到的结果
-
C++ 与 Eclipse (MinGW) 和 Microsoft Visual Studio(禁用语言扩展)仍然输出“正确”的答案,而不是我的预期输出。
标签: c++ inheritance constructor destructor