《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修饰对象。
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值