/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称:下面的程序存在编译错误。有两种方法可以修改,请给出这两种修改方案,
说明我倾向于用哪一种?为什么?处理此类问题的原则是什么?
* 作 者: 张传新
* 完成日期: 2012 年 03 月 25 日
* 版 本 号: 1 。0
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:
* 程序输出:
* 程序头部的注释结束
*/
源程序:
#include<iostream>
using namespace std;
class C
{
private:
int x;
public:
C(int x){this->x = x;}
int getx(){return x;}
};
void main()
{
const C c(5);
cout<<c.getx()<<endl;
system("pause");
}
修改方案一:
#include<iostream>
using namespace std;
class C
{
private:
int x;
public:
C(int x){this->x = x;}
int getx()const{return x;}//将非const型函数改为const型
};
void main()
{
const C c(5);
cout<<c.getx()<<endl;
system("pause");
}
修改方案二:
#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); //将const去掉
cout<<c.getx()<<endl;
system("pause");
}
程序中彩色部分为修改方案。
修改分析:我更倾向于第一种修改方案,将非const型函数改为const型,这样在程序编译过程中不会因为数据的改动,
而产生输出结果的改变,因为const型成员函数中的数据成员是不能修改的。
具体情况如下:
数据成员 | 非const成员函数 | const成员函数 |
非const数据成员 | 可引用,可改变值 | 可引用,不可改变值 |
const数据成员 | 可引用,不可改变值 | 可引用,不可改变值 |
const对象的数据成员 | 不可引用,不可改变 | 可引用,不可改变值 |