【问题标题】:Why can't I mark this member function as const?为什么我不能将此成员函数标记为 const?
【发布时间】:2014-11-30 04:45:36
【问题描述】:

当我尝试编译这个短程序时:

#include <iostream>

class Foo {

public:
    friend int getX() const;

private:
    int x;
};

int Foo::getX() const { return this->x; }

int main() {
    Foo foo;
    std::cout << foo.getX() << std::endl;
}

我收到以下错误:

C:\>gcc test.cpp
test.cpp:6:23: error: non-member function 'int getX()' cannot have cv-qualifier
     friend int getX() const;
                       ^
test.cpp:12:17: error: no 'int Foo::getX() const' member function declared in cl
ass 'Foo'
 int Foo::getX() const { return this->x; }
                 ^
test.cpp: In function 'int main()':
test.cpp:16:22: error: 'class Foo' has no member named 'getX'
     std::cout << foo.getX() << std::endl;
                      ^

为什么我不能在这里将getX() 标记为const?它不会修改Foo 的状态或任何东西,所以我应该可以这样做。

【问题讨论】:

  • 你为什么把它标记为friend
  • 编译器说明了原因。只有成员函数可以是const

标签: c++ constants member-functions


【解决方案1】:

您正在声明一个带有friendconst 的函数。将两者放在一起是没有意义的:friendmember 函数没有意义,因为成员函数已经可以访问类的私有信息。 const 对于 成员函数没有意义,因为没有他们承诺不会修改的固有对象。

【讨论】:

    【解决方案2】:

    问题在于您的friend 声明。它不是声明类的成员,而是声明一个外部非成员函数,该函数将成为该类的朋友。非成员函数不能声明为const。这就是第一个编译器错误所抱怨的。第二个编译器错误是由于您声明的是友谊而不是成员,因此成员主体定义的语法无效 - 没有声明成员,因此您无法定义成员主体。

    您正在尝试创建一个成员方法,因此您需要删除friend 说明符(没有理由将成员声明为朋友):

    class Foo {
    
    public:
        int getX() const;
    
    private:
        int x;
    };
    

    【讨论】:

      【解决方案3】:

      Friend 函数无权访问this,它只能被类成员函数访问。 this 引用了该类的特定实例,而友元函数虽然定义在类文件中,但本质上不是成员函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-15
        • 1970-01-01
        • 2017-12-17
        相关资源
        最近更新 更多