【发布时间】:2016-07-03 05:30:45
【问题描述】:
根据我在课堂上学到的知识,派生类不会继承其父类的:
- 构造函数/析构函数
- 朋友
- 私人会员
但是,如果我们将派生类向上转换为它的父类,我们是否可以访问父类的私有成员,并且父类的朋友现在是否可以应用到这个向上转换的类?
我倾向于认为向上转换的派生类将无法访问父类的私有方法和变量,因为派生类首先不继承它们是有原因的。
(以下代码是在验证答案后添加的)
这个c++代码是用来测试我问的问题的:
#include <iostream>
class A;
void funcGetAVal(A);
class A
{
private:
int aVal;
friend void ::funcGetAVal(A);
public:
A()
{
aVal = 0;
}
};
class B : public A
{
public:
int bVal;
B() : A()
{
bVal = 0;
}
};
void funcGetAVal(A aClass)
{
std::cout << "A val accessed from friend function: " << aClass.aVal << std::endl;
}
int main()
{
B * b = new B;
A * a = new A;
A * bNowA = reinterpret_cast<A *>(b); //This reinterprets the instance of the derived class into an instance of the base class
//std::cout << bNowA->aVal << std::endl; //This caused a compile-time error since aVal is a private member of A
::funcGetAVal(*a); //This calls the funcGetAVal function with an instance of the base class
::funcGetAVal(*bNowA); //This calls the funcGetAVal function with an instance of the derived class reinterpreted as the base class
//Both funcGetAVal function calls print out 0
return 0;
}
结果与 R Sahu 的回答一致。从 B 的实例访问 A 的私有成员导致错误,友元函数能够访问派生类的 aVal。
【问题讨论】:
-
“访问”私有方法和变量是什么意思?无论您如何转换,您都无法访问私有方法和变量。
-
“访问”是指调用函数或将变量与基类一起使用。例如,如果 A 类有一个私有整数:aVal,而 B 类继承了 A,那么如果 B 有一个名为 b 的实例,B 是否可以通过输入 b.aVal 访问 aVal?您的第二句话回答了这个关于私有成员访问的问题。
-
你误解了一些东西。父类完全包含在派生实例中。仅仅因为属性不可用(通过私有),并不意味着属性不存在。永远不需要向上转换(从派生实例到基础对象),也不建议这样做。请重新阅读教科书中的“is-a”讨论。
-
我建议您尝试一下...使用“reinterpret_cast”,写一个minimal reproducible example,并告诉我们您遇到了什么问题。
-
确实,所有的私有变量和方法都会在继承的类中存在,但是你不能直接使用它们,即使你把它上载到父类。这不是因为继承,而是因为函数和变量是私有的。
标签: c++ inheritance friend