gpt4 book ai didi

c++ - 新的运营商 ->有或没有

转载 作者:行者123 更新时间:2023-11-28 01:22:55 25 4
gpt4 key购买 nike

目标

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

我的工作

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

定义类

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

slice employee 对象转换为 person 对象。对象 extraPerson1 是一个 person 对象,而不是一个 employee 对象。当您调用它的 setName 函数时,您正在调用 person::setName

多态性和虚函数只有在你有指针引用时才有效。

关于c++ - 新的运营商 ->有或没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55276012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com