为什么下面的代码无法编译?

Why the following code doesn't compile?

本文关键字:编译 代码 为什么      更新时间:2023-10-16

我有以下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();
}

它就是不能编译。有人能解释一下吗?谢谢

大概是您的编译器告诉您为什么不编译。我说:

In member function ‘void A::f1(const A&)’:
passing ‘const A’ as ‘this’ argument of ‘void A::f2()’ discards qualifiers

这告诉我,您正在尝试对const对象(const A& o)的引用调用非const成员函数(A::f2)。

向函数添加const限定符,以允许在const对象上调用它:

void f2() const
          ^^^^^

或者从引用中删除const以允许修改,但在这种情况下,不要这样做,因为f2()不需要修改对象。

A::f2()需要声明为const才能从const引用中使用。

更改:

void f2()

至:

void f2() const

不能在const对象上调用非const函数。通过将函数声明为const,可以保证它不会更改对象的状态(mutable成员变量除外)。