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.
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.
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;
};
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.