问题
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;
}
I get these errors:
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;
^
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.
回答1:
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.
回答2:
The problem is your friend
statement. It is not declaring a member of the class, it is declaring an outside non-member function that is to be a friend of the class. A non-member function cannot be declared as const
. That is what the first compiler error is complaining about. The second compiler error is due to the fact that you are declaring a friendship and not a member, so the syntax of the definition for the member's body is invalid - there is no member declared, so you cannot define the member's body.
You are trying to create a member method, so you need to remove the friend
specifier (there is no reason to declare members as friends):
class Foo {
public:
int getX() const;
private:
int x;
};
回答3:
Friend functions do not have access to this
, which is only accessible for functions that are members of the class. this
references a specific instance of that class, and by nature friend functions, though defined in the class file, are not member functions.
来源:https://stackoverflow.com/questions/27210102/why-cant-i-mark-this-member-function-as-const