OJ:访问 const 成员函数问题

Description

补足程序使得其输出结果是:

40

#include <iostream>
#include <string>
using namespace std;

struct A {
	int n;
	A() { };
	A(int n_ ):n(n_) { }
// Your Code Here
};
int main()
{
	A c;
	const A a(10);
	c = a + A(30);
	cout << c.n << endl; 
	return 0;
}

Output

40

解法如下:

#include <iostream>
#include <string>
using namespace std;

struct A {
	int n;
	A() { };
	A(int n_ ):n(n_) { }
	
	int operator+(struct A b) const{
		return this->n + b.n;
	}
};
int main()
{
	A c;
	const A a(10);
	c = a + A(30);
	cout << c.n << endl; 
	return 0;
}

本题注意事项:C++ 中 const 修饰的对象只能访问该对象的 const 函数,因为其他函数有可能会修改该对象的成员,编译器为了避免该类事情发生,会认为调用非 const 函数是错误的。函数末尾加 const,表示不会修改该对象的成员。

posted @ 2018-05-17 20:47  Zackary丶Liu  阅读(175)  评论(0)    收藏  举报