* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:
* 作 者: 吴瑕
* 完成日期: 2012 年 03 月 13 日
* 版 本 号:
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:下面的程序存在编译错误。有两种方法可以修改,请给出这两种修改方案,在报告中说明你倾向于用哪一种?为什么?处理此类问题的原则是什么?
#include <iostream> using namespace std; class C { private: int x; public: C(int x){this->x = x;} int getX() const{return x;}//将成员函数定义为常成员函数 }; void main() { const C c(5); cout<<c.getX(); system("pause"); } 因为对象c被定义为了常对象,常对象只能引用常成员函数。 #include <iostream> using namespace std; class C { private: int x; public: C(int x){this->x = x;} int getX() {return x;} }; void main() { C c(5);//将对象定义为一般的对象 cout<<c.getX(); system("pause"); }
上机感言:
我认为第一种方法更好,因为把一个对象定义为常对象以后,类中的数据成员不会再被改变,保证了其安全性! 要使某个类中的全部数据成员的值不被改变最好用第一种方法!