新的运营商 - >有或没有

new operator -> with or without

Objective

尝试了解实例化派生 class 对象的行为差异

我的作品

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

已定义 classes

I created a base class "person" and a derived class "employee" as below

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 的行为。

I fail to understand why extraPerson1 and extraPerson2 behave differently even though both seem to have similar initiations.

请帮忙!

person extraPerson1 = employee();

sliceemployee对象变成了person对象。对象 extraPerson1person 对象而不是 employee 对象。当您调用其 setName 函数时,您正在调用 person::setName.

多态性和虚函数只有在你有 pointersreferences.

时才有效