问题 问答题

使用VC6打开考生文件夹下的工程RevProj12。此工程包含一个源程序文件RevMain12.cpp,但在该程序中有错误。请改正程序中的错误,使它能得到正确结果。 注意:不得删行或增行,也不得更改程序的结构。 源程序文件RevMain12.cpp中的程序清单如下: //RevMain12.cpp #include<iostream> /* * * * FOUND * * * * */ using namespace std; class test { private: const int value; char dep[10]; public: /* * * * *FOUND* * * * */ test() {value=0;strcpy(dep,"m"); } /* * * * *FOUND* * * * */ test(int newvalue) {value=newvalue; strcpy (dep, "m");}/* * * * *FOUND * * * * */void show(){ cout<<"value= "<<value<<end1;} }; int main () {test t1;const test t2;t1.show ();t2.show();return 0; }

答案

参考答案:

解析:正确的类定义为: #include<iostream> #include<string> using namespace std; class test { private: const int value; char dep[10]; public: test():value(0) { strcpy(dep,"m"); } test(Int newvalue):value(newvalue) { strcpy(dep,"m"); } void show() const { cout<<"value="<<value<<end1; } }; 该程序类定义中有以下错误: ①类中的常量成员value的初始化工作应放在构造函数的初始化列表中,所以两个构造函数的定义应该改为; test():value(0) {strcpy(dep,"m");} test(int newvalue):value(newvalue) {strcpy(dep,"m");} ②程序中用到了库函数strcpy(),因此需要在程序的开头处加上:#include<string>。 ③程序的主函数中定义了常对象t2,因此借助对象t2不能调用非常成员函数show(),为保证程序能够正常运行,可将成员函数show()改为常成员函数。

选择题
单项选择题