/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2012, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称: 程序修改(const)
* 作 者: 刘镇
* 完成日期: 2012 年 3 月 25 日
* 版 本 号: 1.040
* 对任务及求解方法的描述部分
* 输入描述:......
* 问题描述: 下面的程序存在编译错误。有两种方法可以修改,给出这两种修改方案
* 程序输出: 5
* 程序头部的注释结束
*/
错误代码:
#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();
system("pause");
}
Error:cpp(18) : error C2662: “C::getX”: 不能将“this”指针从“const C”转换为“C &”
第一种修改:改动成员函数,变为常成员函数。
#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");
}
第二种修改:改动常对象。
#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就是对其进行保护,或者说是进行限制罢了。