我如何看到地址和值C ++类之间的区别? [英] How can i see the difference between address and value c++ class?
本文介绍了我如何看到地址和值C ++类之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在指针和参考理解方面有问题.我有以下代码段:
I have a problem in pointers and reference understanding. I have the following snippet:
class U
{
protected:
int m;
public:
U(int m = 0) : m(m) {}
virtual void f() { cout << "U::f() @ m = " << m << endl; }
};
class V : public U
{
int n;
public:
V(int m, int n) : U(m), n(n) {}
void f() { cout << "V::f() @ m = " << m << ", n = " << n << endl; }
};
int main() {
V v1(1, 1), v2(2, 2);
v1.f();
v2.f();
U* u = &v1;
*u = v2;
v1.f();
v2.f();
}
我运行此命令,输出为:
I run this and the output is:
V::f() @ m = 1, n = 1
V::f() @ m = 2, n = 2
V::f() @ m = 2, n = 1
V::f() @ m = 2, n = 2
我不明白输出的第三行: V :: f()@ m = 2,n = 1
.为什么将 m
更改为 2
?
I don't understand the third line of output: V::f() @ m = 2, n = 1
. Why m
is changed to 2
?
推荐答案
*u=v2;
这不会使 u
指向 v2
.它将 v2
分配给 u
指向的对象的 U
子对象,即 U
部分的 v1
.这是因为 * u
是 U
对象.
This doesn't make u
point to v2
. It assigns v2
to the U
sub-object of the object that u
points to, i.e. to the U
part of v1
. This is because *u
is a U
object.
这篇关于我如何看到地址和值C ++类之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文