#include<iostream.h> using namespace std; class Base {public: Base(){cout<<" construct in Base\n";} virtual ~Base() {cout<<" destruting Base "<<endl;} }; class Subclass:public Base { public: Subclass() {cout<<" construct in Subclass\n";} ~SubclassO {cout<<" destruting subclass"<<endl;} }; void test (Base* x) {delete x; } int main() {cout<<"first:\n"; Base *bc=new Base ; cout<<"second\n"; Subclass * sc=new Subclass; cout<<" calling test(be)\n"; test(be); cout<<"calling test(se)\n" test(sc); cout<<"end!\n"; return 0;结果是什么
时间: 2024-03-08 15:50:32 浏览: 62
#include_iostream.h_
4星 · 用户满意度95%
这段代码存在多处语法错误,无法通过编译。以下是修正后的代码:
```c++
#include <iostream>
using namespace std;
class Base {
public:
Base() {
cout << "construct in Base\n";
}
virtual ~Base() {
cout << "destructing Base\n";
}
};
class Subclass : public Base {
public:
Subclass() {
cout << "construct in Subclass\n";
}
~Subclass() {
cout << "destructing Subclass\n";
}
};
void test(Base* x) {
delete x;
}
int main() {
cout << "first:\n";
Base* bc = new Base;
cout << "second:\n";
Subclass* sc = new Subclass;
cout << "calling test(bc):\n";
test(bc);
cout << "calling test(sc):\n";
test(sc);
cout << "end!\n";
return 0;
}
```
运行结果为:
```
first:
construct in Base
second:
construct in Base
construct in Subclass
calling test(bc):
destructing Base
calling test(sc):
destructing Subclass
destructing Base
end!
```
说明程序先创建了一个 Base 对象和一个 Subclass 对象,然后调用了 test 函数分别删除了它们,最后输出了一些信息。注意到 Subclass 的析构函数会先调用子类的析构函数,再调用基类的析构函数。
阅读全文