为什么不能将此成员函数标记为const? [英] Why can't I mark this member function as const?

查看:39
本文介绍了为什么不能将此成员函数标记为const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试编译此简短程序时:

When I try to compile this short program:

#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 的状态或其他任何内容,因此我应该能够这样做。

Why can't I mark getX() as const here? It doesn't modify Foo's state or anything, so I should be able to do so.

推荐答案

您要同时声明 friend const 的函数。两者都没有意义: friend member 函数没有意义,因为成员函数已经可以访问该班级的私​​人学生。 const 对于 non 成员函数没有意义,因为没有内在对象会承诺不会对其进行修改。

You're declaring a function with both friend and const. It doesn't make sense to have both together: friend isn't meaningful for member functions because member functions already have access to the class's privates. const isn't meaningful for non-member functions because there's no inherent object that they'd promise not to modify.

这篇关于为什么不能将此成员函数标记为const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆