题1:实现下列程序,编译并运行,如果有错误请纠正(实验报告中写明出错的原因及相关知 识点),并给出输出结果。 #include<iostream> usingnamespacestd; classBase{ public: Base(){a=5;cout<<"Basea="<<a<<endl;} protected: inta; }; classBase1:publicBase{ public: intb1; Base1(){a=a+10;cout<<"Base1a="<<a<<endl;} }; classBase2:publicBase{ public: intb2; Base2(){a=a+20;cout<<"Base2a="<<a<<endl;} }; classDerived:publicBase1,publicBase2{ public: intd; Derived(){ cout<<"Base1::a="<<Base1::a<<endl; cout<<"Base2::a="<<Base2::a<<endl; cout<<"Deriveda="<<a<<endl; } }; main(){ Derivedobj; return0; }
时间: 2023-10-30 18:13:49 浏览: 126
题1答案:
程序中存在以下几个错误:
1. 在类Base的构造函数中,缺少访问修饰符public,应该将Base()修改为public: Base()。
2. 在main函数中,缺少int类型的返回值,应该将main()修改为int main()。
3. 在Derived类的构造函数中,应该在Base1和Base2的构造函数中分别调用它们的构造函数,以初始化变量a,否则会出现未定义的结果。
修改后的程序如下:
```
#include<iostream>
using namespace std;
class Base{
public:
Base(){
a=5;
cout<<"Base a="<<a<<endl;
}
protected:
int a;
};
class Base1: public Base{
public:
int b1;
Base1(){
a=a+10;
cout<<"Base1 a="<<a<<endl;
}
};
class Base2: public Base{
public:
int b2;
Base2(){
a=a+20;
cout<<"Base2 a="<<a<<endl;
}
};
class Derived: public Base1, public Base2{
public:
int d;
Derived(){
Base1();
Base2();
cout<<"Base1::a="<<Base1::a<<endl;
cout<<"Base2::a="<<Base2::a<<endl;
cout<<"Derived a="<<a<<endl;
}
};
int main(){
Derived obj;
return 0;
}
```
输出结果为:
```
Base a=5
Base2 a=25
Base1 a=15
Base1::a=15
Base2::a=25
Derived a=15
```
阅读全文