#include <iostream> using namespace std; class BASE{ protected: int id; public: BASE() : id(0) {} int update(int n) { id += n; return id; } virtual void hello(){ cout << "BASE" << endl; } }; class DERIVED : public BASE { public: DERIVED () { id = 1;} int update(int n) { id += 2*n; return id;} void hello() { cout << "DERIVED " << endl; } }; int main () { BASE* objs[2]; objs[0] = new BASE(); objs[1] = new DERIVED (); for(int i=0; i<2; i++) { objs[i]->hello(); cout << objs[i]->update(10) << endl; } return 0; }
时间: 2024-03-27 15:41:49 浏览: 25
这段代码是一个简单的面向对象的C++程序,包含了基类和派生类的定义以及一个主函数。
在这段代码中,有两个类:BASE和DERIVED。BASE类有一个保护类型的成员变量id和一个公有类型的成员函数update,update函数的作用是将id加上传入的参数n并返回id的值。同时,BASE类还有一个虚函数hello,输出字符串“BASE”。
DERIVED类是从BASE类派生而来的,它的构造函数将id初始化为1。DERIVED类也有一个名为update的成员函数,但与BASE类中的update函数不同的是,它将id加上2倍的传入参数n并返回id的值。DERIVED类还重写了hello函数,输出字符串“DERIVED”。
在主函数中,定义了一个长度为2的BASE类型的指针数组objs,分别指向BASE类和DERIVED类的对象。在循环中,先调用hello函数输出对应的字符串,再调用update函数将id加上10,并输出最终的id值。
该程序的输出结果为:
BASE
10
DERIVED
21
因为objs[0]指向BASE类的对象,输出字符串“BASE”,并将id加上10后输出10;objs[1]指向DERIVED类的对象,输出字符串“DERIVED”,并将id加上20后输出21。
相关问题
#include<iostream> using namespace std class Base{ protected: Base(){cout<<'A';} Base(charc){cout<<c;}}; class Derived:public Base{ public: Derived(char c){cout<<c;}}; int main() {Derived dl('B'); return 0;} 执行这个程序屏幕上将显示输出
程序中存在语法错误,正确的代码应该是这样的:
```
#include<iostream>
using namespace std;
class Base {
protected:
Base() {
cout << 'A';
}
Base(char c) {
cout << c;
}
};
class Derived : public Base {
public:
Derived(char c) : Base(c) {
cout << c;
}
};
int main() {
Derived dl('B');
return 0;
}
```
运行结果是:`AB`。因为在创建 Derived 对象时会先调用 Base 的构造函数,然后再调用 Derived 的构造函数。在 Base 的默认构造函数中输出了字符 A,在 Base 的带参构造函数和 Derived 的构造函数中输出了字符 B。所以最终输出的结果是 AB。
请指出下面程序中的错误代码并说出错误原因和改错方法include<iostream> using namespace std; class Base1{ protected: int m; public: void Show(){cout<<m<<endl;} } ; class Base2 { protected: int n; public: void Show(){cout<<n<<endl;} } ; class Derived:public Base1, public Base2 { public: void Set( int x, int y ) {m=x;n=y;} } ; int main() { Derived Obj; Obj. Set(45,87); Obj. Show(); return 0; }
错误代码如下:
```c++
#include <iostream>
using namespace std;
class Base1 {
protected:
int m;
public:
void Show() { cout << m << endl; }
};
class Base2 {
protected:
int n;
public:
void Show() {cout << n << endl;}
};
class Derived : public Base1, public Base2 {
public:
void Set(int x, int y) { m = x; n = y; }
using Base1::Show; // 解决方法1:引入 using 声明
};
int main() {
Derived Obj;
Obj.Set(45, 87);
Obj.Show(); // 错误:调用 Show() 不明确
return 0;
}
```
错误原因:`Derived` 类从两个基类继承了同名的 `Show()` 函数,导致在 `main()` 函数中调用 `Obj.Show()` 时编译器无法确定该调用哪个基类的 `Show()` 函数。
改错方法:
1. 引入 `using` 声明,显式指定调用哪个基类的 `Show()` 函数。
2. 修改派生类 `Derived` 中的 `Show()` 函数,避免与基类 `Base1` 和 `Base2` 的函数名称冲突。