Derived Classes Cannot Access Private Members
在C++中:该概念是派生类对象,成员函数无法访问父类的私有成员。但是,如果父类的公共成员函数返回私有变量的引用,并且父类在子类中是公共继承的,而子类具有一个函数(在本例中是display()),该函数从父类(在本例中是show())调用函数并引用私有变量x,该怎么办呢?addreA的ss应该与X匹配,但我不知道为什么不同?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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; } |
输出:0x7FFE5B71BB00x7FFE5B71BB4
我不明白地址更改背后的概念是什么,因为我正在传递一个对私有变量的引用。
当你写作时
1 | int a = show(); |
您的意思是"生成一个名为
要修复此问题,请将代码更改为
1 | int& a = show(); |
这表示"创建一个新的
请注意,这与继承无关。它纯粹是复制
这里只显示局部变量
更改为
整数是一个值。例如,如果使用自定义类而不是整数,则会得到相同的地址。但是,作为值类型,所有整型变量在内存中都有各自独立的空间。要使用相同的地址,变量
1 2 3 4 | void display() { int* a=show(); cout<<a<<endl; } |
更改后,地址应该是相同的。请注意,我在输出中删除了
来源(https://www.cprogramming.com/tutorial/lesson6.html):
Pointing to Something: Retrieving an Address
In order to have a pointer actually point to another variable it is
necessary to have the memory address of that variable also. To get the
memory address of a variable (its location in memory), put the & sign
in front of the variable name. This makes it give its address. This is
called the address-of operator, because it returns the memory address.
Conveniently, both ampersand and address-of start with a; that's a
useful way to remember that you use & to get the address of a
variable.For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 #include <iostream>
using namespace std;
int main() {
int x; // A normal integer
int *p; // A pointer to an integer
p = &x; // Read it,"assign the address of x to p"
cin>>x; // Put a value in x, we could also use *p here
cin.ignore();
cout<< *p <<"
"; // Note the use of the * to get the value
cin.get();
}
编辑:出错了,我写这封信的时候有人回答了。