#include <iostream> using namespace std; class Base1 { protected: int data1; public: Base1(int a = 8) { data1 = a; cout << data1 << ", Base1 Constructor\n"; } ~Base1() { cout << data1 << ", Base1 Destructor\n"; } }; class Base2 { protected: int data2; public: Base2(int a = 9) { data2 = a; cout << data2 << ", Base2 Constructor\n"; } ~Base2() { cout << data2 << ", Base2 Destructor\n"; } }; class Derived :public Base1, public Base2 { int d; public: Derived(int x, int y, int z) : Base1(x), Base2(y) //A { d = z; cout << "Derived Constructor\n"; } ~Derived() { cout << "Derived Destructor\n"; } void Show() { cout << data1 << ',' << data2 << ',' << d << endl; } }; int main() { Derived c(1, 2, 3); c.Show(); return 0; }以上C++代码调试时显示有一个错误,怎么解决?
时间: 2024-03-20 09:41:42 浏览: 80
使用include <iostream>时一定要加using namespace std
在代码的构造函数`Derived(int x, int y, int z) : Base1(x), Base2(y)`后面没有加上大括号`{}`,导致编译器无法正确识别构造函数的定义,因此报错。
正确的代码应该是:
```c++
#include <iostream>
using namespace std;
class Base1 {
protected:
int data1;
public:
Base1(int a = 8) {
data1 = a;
cout << data1 << ", Base1 Constructor\n";
}
~Base1() {
cout << data1 << ", Base1 Destructor\n";
}
};
class Base2 {
protected:
int data2;
public:
Base2(int a = 9) {
data2 = a;
cout << data2 << ", Base2 Constructor\n";
}
~Base2() {
cout << data2 << ", Base2 Destructor\n";
}
};
class Derived :public Base1, public Base2 {
int d;
public:
Derived(int x, int y, int z) : Base1(x), Base2(y) {
d = z;
cout << "Derived Constructor\n";
}
~Derived() {
cout << "Derived Destructor\n";
}
void Show() {
cout << data1 << ',' << data2 << ',' << d << endl;
}
};
int main() {
Derived c(1, 2, 3);
c.Show();
return 0;
}
```
以上代码中,在`Derived`类定义后面加上了大括号`{}`,用于定义构造函数和析构函数的内容。这样就可以正确识别构造函数的定义,消除了编译器报错。
阅读全文