试图了解实例化派生类对象的行为差异
我创建了一个基类“person”和一个派生类“employee”,如下所示
人
class person
{
protected:
string name;
public:
person();
~person();
virtual void setName(string myName)
{
name = myName;
}
};
雇员
class employee : public person
{
public:
employee();
~employee();
void setName(string myName)
{
name = myName+"さん";
}
};
int main()
{
person newPerson = person();
employee anotherPerson1 = employee();
employee* anotherPerson2 = new employee();
person extraPerson1 = employee();
person* extraPerson2 = new employee();
newPerson.setName("new");
anotherPerson1.setName("another1");
anotherPerson2->setName("another2");
extraPerson1.setName("extra1");
extraPerson2->setName("extra2");
cout << newPerson.getName() << endl;
cout << anotherPerson1.getName() << endl;
cout << anotherPerson2->getName() << endl;
cout << extraPerson1.getName() << endl;
cout << extraPerson2->getName();
}
new
another1さん
another2さん
extra1
extra2さん
我理解newPerson,anotherPerson1和anotherPerson2的行为。
我无法理解为什么extraPerson1和extraPerson2表现不同,即使两者似乎都有类似的启动。
请帮忙!
同
person extraPerson1 = employee();
你slice employee
对象成为person
对象。对象extraPerson1
是person
对象而不是employee
对象。当你调用它的setName
函数时,你正在调用person::setName
。
只有指针或引用才能使用多态和虚函数。