/*
* Copyright (c) 2012, 烟台大学计算机学院
* All rights reserved.
* 文件名称:123.cpp
* 作 者: 邱学伟
* 完成日期:2013 年 4 月 5 日
* 版 本 号:v1.0
* 输入描述:无
* 问题描述: 改错题,程序中有一个错误找出来并改正
* 程序输出:略
* 问题分析:略
算法设计:略
*/
#include<iostream>
#include<stdlib.h>
using namespace std;
class C
{private:
int x;
public:
C(int x){this->x = x;}
int getX() {return x;}
};
int main()
{
const C c(5);
cout<<c.getX();
return 0;
}
第一种方法:
#include<iostream> #include<stdlib.h> using namespace std; class C {private: int x; public: C(int x){this->x = x;} int getX() const {return x;} }; int main() { const C c(5); cout<<c.getX(); return 0; }
说明:const成员函数可以访问const成员数据和非成员数据
第二种方法:
#include<iostream> #include<stdlib.h> using namespace std; class C {private: int x; public: C(int x){this->x = x;} int getX() {return x;} }; int main() { C c(5); cout<<c.getX(); return 0; }
说明:const数据不能被改变