新操作员 - >有或没有

问题描述 投票:0回答:1

Objective

试图了解实例化派生类对象的行为差异

My work

  1. 创建了一个班级“人”
  2. 向“person”类添加了一个虚拟方法,将值设置为变量名
  3. 定义了从基类“person”派生的类“employee”
  4. 向“employee”类添加了一个方法,该方法将值设置为最初在基类中定义的变量名,但在其后添加“さん”后缀。
  5. 创建了不同类型的启动并测试了输出之间的差异

Defined classes

我创建了一个基类“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+"さん";
    }
};

Main

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();
}

Console output

new
another1さん
another2さん
extra1
extra2さん

Question

我理解newPerson,anotherPerson1和anotherPerson2的行为。

我无法理解为什么extraPerson1和extraPerson2表现不同,即使两者似乎都有类似的启动。

请帮忙!

c++ oop new-operator
1个回答
2
投票

person extraPerson1 = employee();

slice employee对象成为person对象。对象extraPerson1person对象而不是employee对象。当你调用它的setName函数时,你正在调用person::setName

只有指针或引用才能使用多态和虚函数。

© www.soinside.com 2019 - 2024. All rights reserved.