【发布时间】:2018-04-19 07:04:17
【问题描述】:
在 C++ 中:
这个概念是派生类对象和成员函数不能访问父类的私有成员。但是,如果父类的公共成员函数返回私有变量的引用,并且父类在子类中是公开继承的,并且子类有一个从父类调用该函数的函数(在本例中为 display()),该怎么办?类(在本例中为 show())并获取私有变量 x 的引用。 a 的地址应该匹配 x 但我不知道为什么它不同?
enter code here
#include <iostream>
using namespace std;
class test{
int x=10;
public:
int & show();
};
class ChildTest: public test{
public:
void display(){
int a=show();
cout<<&a<<endl;
}
};
int & test::show(){
cout<<&x<<endl; //so this address should match the above address but it //is not matching I don't understand why?
return x;
}
int main()
{
ChildTest obj;
obj.display();
return 0;
}
输出:
0x7ffe5b751bb0
0x7ffe5b751bb4
鉴于我正在传递对私有变量的引用,我不明白地址更改背后的概念是什么。
【问题讨论】:
标签: c++ inheritance reference