我有以下C++代码:
#include <iostream>
#include <vector>
using namespace std;
class A
{
private:
int i;
public:
void f1(const A& o);
void f2()
{
cout<<i<<endl;
}
};
void A::f1(const A& o)
{
o.f2();
}
Run Code Online (Sandbox Code Playgroud)
它只是不编译.有人可以解释一下吗?谢谢!
据推测,你的编译器告诉你它为什么不编译.我说:
In member function ‘void A::f1(const A&)’:
passing ‘const A’ as ‘this’ argument of ‘void A::f2()’ discards qualifiers
Run Code Online (Sandbox Code Playgroud)
这告诉我你正在尝试在对象()的引用上调用非const成员函数().A::f2constconst A& o
const向函数添加限定符以允许在const对象上调用它:
void f2() const
^^^^^
Run Code Online (Sandbox Code Playgroud)
或者const从引用中删除以允许修改 - 但在这种情况下,不要这样做,因为f2()不需要修改对象.
A::f2()需要声明const从您的const参考中使用.
更改:
void f2()
Run Code Online (Sandbox Code Playgroud)
至:
void f2() const
Run Code Online (Sandbox Code Playgroud)
您无法const在const对象上调用非函数.通过声明函数,因为const您保证它不会更改对象的状态(mutable成员变量除外).