/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:class Student
* 作 者: 刘程程
* 完成日期: 2012 年 03 月 26 日
* 版 本 号: 1.0
* 文件名称:下面的程序存在编译错误。有两种方法可以修改,请给出这两种修改方案,说明我倾向于用哪一种?为什么?处理此类问题的原则是
什么?
方案1:
#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");
}
原因:如果一个对象被声明为常对象,则不能调用该对象的非const型的成员函数。所以将const C c(5);前面的const去掉即可。
方案2:
#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");
}
原因:将常对象中的非const 型成员函数变成常成员函数即可。
我更倾向于选择第二种方案,因为第二种增加了数据的安全性,保证其数据成员的值不被修改!