咋么在多态数组中用set方法赋值

img


多态数组为啥像第一个person[0]直接这样赋值不可以,应该这么赋值呢,

初始化 person数组,不代表每个元素初始化了
加上
person[0] = new Person();

person[0].setName(...)

【以下回答由 GPT 生成】

你好!对于多态数组中的对象,不能直接使用赋值运算符来进行赋值。相反,你可以使用指针或引用来操作数组中的对象,并调用对象的set方法来进行赋值。

下面是一个示例代码,来展示如何在C++多态数组中使用set方法进行赋值:

#include <iostream>

class Person {
public:
    virtual void set(const std::string& name) {
        this->name = name;
    }

    virtual void print() const {
        std::cout << "Name: " << name << std::endl;
    }

protected:
    std::string name;
};

class Student : public Person {
public:
    void set(const std::string& name, int studentId) {
        this->name = name;
        this->studentId = studentId;
    }

    void print() const {
        std::cout << "Name: " << name << ", Student ID: " << studentId << std::endl;
    }

private:
    int studentId;
};

int main() {
    const int ARRAY_SIZE = 2;
    Person* person[ARRAY_SIZE];

    Student student1;
    student1.set("John Doe", 12345);
    person[0] = &student1;

    Student student2;
    student2.set("Jane Smith", 67890);
    person[1] = &student2;

    // 使用set方法给person[0]赋值
    person[0]->set("Mark Johnson", 98765);

    // 打印数组中的对象
    for (int i = 0; i < ARRAY_SIZE; i++) {
        person[i]->print();
    }

    return 0;
}

在这个例子中,我们首先定义了一个名为Person的基类,其中包含了一个set方法和一个print方法。然后,我们定义了一个名为Student的派生类,它重写了set方法和print方法,并添加了一个新的成员变量studentId。

在主函数中,我们创建了一个多态数组person,数组类型为指向Person对象的指针。然后,我们创建了两个Student对象,并使用set方法分别给它们赋值。接下来,我们使用set方法给person[0]赋值,并使用print方法打印数组中的对象。

运行这段代码,你会看到person[0]被成功赋值为"Mark Johnson",并将其打印出来。

希望这可以帮助到你!如果你还有任何问题,请随时提问。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^