/* (程序头部注释开始)
* 程序的版权和版本声明部分
* Copyright (c) 2011, 烟台大学计算机学院学生
* All rights reserved.
* 文件名称: const.cpp
* 作 者: 苗向前
* 完成日期: 2012 年 03 月26 日
* 版 本 号: V6.1
* 对任务及求解方法的描述部分
* 输入描述:
* 问题描述:
* 程序输出:
* 程序头部的注释结束
*/(1)
#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");
}
(2)
#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声明一下是很有必要的,
而且有时候也需要保证函数不会改变数据,所以用常成员函数也是很有必要的。