#include <iostream> using namespace std; class BaceClass { public: BaceClass(); }; BaceClass::BaceClass() { cout << "构造基类对象" << endl; }; class DerivedClass : public BaseClass { public: DerivedClass(); }; DerivedClass::DerivedClass() { cout << "构造派生类对象" << endl; } int main(int argc, char** argv) { DerivedClass d; return 0; }哪里错了
时间: 2024-03-23 14:41:17 浏览: 65
程序员面试宝典题目总结
5星 · 资源好评率100%
代码中有一个类名拼写错误,将 `BaceClass` 改为 `BaseClass` 即可,另外需要将基类的构造函数改为 `virtual`,否则派生类的构造函数不会调用基类的构造函数。
正确的代码如下:
```
#include <iostream>
using namespace std;
class BaseClass {
public:
virtual BaseClass();
};
BaseClass::BaseClass() {
cout << "构造基类对象" << endl;
};
class DerivedClass : public BaseClass {
public:
DerivedClass();
};
DerivedClass::DerivedClass() {
cout << "构造派生类对象" << endl;
}
int main(int argc, char** argv) {
DerivedClass d;
return 0;
}
```
阅读全文