问题
class baseClass {
public:
friend int friendFuncReturn(baseClass &obj) { return obj.baseInt; }
baseClass(int x) : baseInt(x) {}
private:
int baseInt;
};
class derivedClass : public baseClass {
public:
derivedClass(int x, int y) : baseClass(x), derivedInt(y) {}
private:
int derivedInt;
};
in the function friend int friendFuncReturn(baseClass &obj) { return obj.baseInt; }
I don't understand why would the friend function of the base class work for the derived class?
should not passing derived class obj. instead of a base class obj. tconsidered as error?
my question is why it works when i pass a derived class object to it?
回答1:
Are friend functions inherited?
No, friend functions are not inherited.
Why would a base class function work on a derived class object?
Because friend function is using the data members available in base class
only. Not the data members of derived class
. Since derived class
is a type of base class
So, friend function is working fine. But note that here derived class
instance is sliced
and having information available only for base class
.
friend function
will report an error if you will try to access restricted members of derived class
. e.g.
int friendFuncReturn(baseClass &obj) { return ((derivedClass)obj).derivedInt; }
回答2:
No. You cannot inherited friend function in C++. It is strictly one-one relationship between two classes.
C++ Standard, section 11.4/8
Friendship is neither inherited nor transitive.
来源:https://stackoverflow.com/questions/47469715/are-friend-functions-inherited-and-why-would-a-base-class-friend-function-work