问题描述
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;
};
在功能friend int friendFuncReturn(baseClass &obj) { return obj.baseInt; }
中的
我不明白为什么基类的友函数对派生类起作用?不应传递派生类obj.而不是基类obj.被视为错误?我的问题是,当我将派生类对象传递给它时,为什么它起作用?
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?
推荐答案
不,不继承好友功能.
因为朋友功能仅使用base class
中可用的数据成员.不是derived class
的数据成员.由于derived class
是base class
的一种类型,因此,朋友功能可以正常工作.但是请注意,这里的derived class
实例是sliced
,并且仅可用于base class
的信息.如果您尝试访问derived class
的受限成员,则friend function
将报告错误.例如
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; }
这篇关于是否继承了朋友功能?为什么基类FRIEND函数在派生类对象上起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!