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,表示不会修改该对象的成员。
感谢花费宝贵的时间浏览,
转载请注明出处。
本人将在[资源共享]分类下陆续加入学习过程中一些比较重要且有用处的资料、源码,大家可前往下载,一起进步。
感谢支持!

浙公网安备 33010602011771号