`
txf2004
  • 浏览: 6865848 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

《C++第六周实验报告1-1》-----程序改错

 
阅读更多
/*
下面的程序存在编译错误。有两种方法可以修改,请给出这两种修改方案,
在报告中说明你倾向于用哪一种?为什么?处理此类问题的原则是什么?
*/
#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");
}
//法一
#include <iostream>

using namespace std;

class C
{
private:
	int x;
public:
	C(int x){this->x = x;}
	int getX(){return x;}//将getX定义为常函数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()
{
	const C c(5);//将const去掉
	cout<<c.getX();
	system("pause");
}
/*
如果就单纯的运行主函数中的内容的话我更倾向于第二种,
因为它保证了数据的安全性,不会更改对象中的数据;
但如果类中还有其他的非常函数的话,不能实现调用,显得不够灵活。
处理此问题就要根据实际的需要进行操作,若没有其他函数就用const修饰对象。
*/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics