多态性:成员访问和 getter 给出不同的结果
Polymorphism: member acces and getter give different results
代码如下:
#include <iostream>
#include <vector>
#include <array>
class Parent
{
public:
virtual void whatAmI(){std::cout << "A Parent" << std::endl;}
virtual long getValue(){std::cout << "value from Parent " << std::endl; return value;}
long value;
};
class Child : public Parent
{
public:
virtual void whatAmI(){std::cout << "A child" << std::endl;}
virtual long getValue(){std::cout << "value from Child " << std::endl; return value;}
long value;
};
class SomeClass
{
public:
Parent * parent;
};
int main()
{
Child c = Child();
SomeClass sc;
sc.parent = &c;
sc.parent->value = 10;
sc.parent->whatAmI();
std::cout << sc.parent->value << std::endl;
std::cout << sc.parent->getValue() << std::endl;
}
它returns:
A child
10
value from Child
0
我已经阅读了有关 object 切片的内容,并确保在 child 被切片后我会分配值 10。我仍然不明白为什么直接字段访问和函数调用会给出不同的结果。
谢谢。
这里没有切片 - 您正在通过指针访问。
该行为是由于成员变量访问是不是多态的。所以 parent->value
总是指 Parent::value
,从不指 Child::value
。而 value
(在 Child::getValue
中)指的是 Child::value
。
代码如下:
#include <iostream>
#include <vector>
#include <array>
class Parent
{
public:
virtual void whatAmI(){std::cout << "A Parent" << std::endl;}
virtual long getValue(){std::cout << "value from Parent " << std::endl; return value;}
long value;
};
class Child : public Parent
{
public:
virtual void whatAmI(){std::cout << "A child" << std::endl;}
virtual long getValue(){std::cout << "value from Child " << std::endl; return value;}
long value;
};
class SomeClass
{
public:
Parent * parent;
};
int main()
{
Child c = Child();
SomeClass sc;
sc.parent = &c;
sc.parent->value = 10;
sc.parent->whatAmI();
std::cout << sc.parent->value << std::endl;
std::cout << sc.parent->getValue() << std::endl;
}
它returns:
A child
10
value from Child
0
我已经阅读了有关 object 切片的内容,并确保在 child 被切片后我会分配值 10。我仍然不明白为什么直接字段访问和函数调用会给出不同的结果。
谢谢。
这里没有切片 - 您正在通过指针访问。
该行为是由于成员变量访问是不是多态的。所以 parent->value
总是指 Parent::value
,从不指 Child::value
。而 value
(在 Child::getValue
中)指的是 Child::value
。