修改下列程序的错误使其可以运行:#include <iostream> // 预处理命令 using namespace std // 使用标准命名空间std class A { private: // 数据成员: int a; // 数据成员 public: // 公有函数: A(int x): a(x){ } // 构造函数 virtual void Show() const{ cout << a; } // 显示a之值 }; template <class ElemType> class B: public A { private: // 数据成员: ElemType b; // 数据成员 public: // 公有函数: B(int x, ElemType y): A(x), b(y){ } // 构造函数 void Show() const { A::Show(); // 调用A的Show() cout << " " << b << endl; // 显示b之值 } }; int main(void) // 主函数main(void) { Bobj(8, "is my happy digit!"); // 定义对象 obj.Show(); // 显示相关信息 system("PAUSE"); // 调用库函数system( ),输出系统提示信息 return 0; // 返回值0, 返回操作系统 }
时间: 2023-06-25 19:04:25 浏览: 61
修改后的程序如下:
```c++
#include <iostream> // 预处理命令
using namespace std; // 使用标准命名空间std
class A {
private:
int a; // 数据成员
public:
A(int x): a(x){ } // 构造函数
virtual void Show() const{ cout << a; } // 显示a之值
};
template <class ElemType>
class B: public A {
private:
ElemType b; // 数据成员
public:
B(int x, ElemType y): A(x), b(y){ } // 构造函数
void Show() const {
A::Show(); // 调用A的Show()
cout << " " << b << endl; // 显示b之值
}
};
int main(void) {
B<string> obj(8, "is my happy digit!"); // 定义对象
obj.Show(); // 显示相关信息
system("PAUSE"); // 调用库函数system( ),输出系统提示信息
return 0; // 返回值0, 返回操作系统
}
```
修改的地方:
1. 在使用类 `B` 前需要指定类型参数 `ElemType`,因此在 `main` 函数中定义 `obj` 时,需要将类型参数指定为 `string`,即 `B<string>`。
2. 将 `Bobj` 改为 `obj`,因为定义对象时应该使用类名加上圆括号括起来的参数列表。
3. 将 `obj.Show()` 改为 `obj.Show()`,因为前面定义的对象名为 `obj`,而不是 `Bobj`。
4. 在程序开头添加 `#include <string>`,以便使用 `string` 类型。
5. 在 `system("PAUSE")` 前加上 `system("pause")`,因为 Windows 系统中命令行窗口不区分大小写。