【发布时间】: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