【问题标题】:How to use a member function from a parent class with the same name (via this->)?如何使用同名父类的成员函数(通过this->)?
【发布时间】:2025-12-21 15:05:12
【问题描述】:

这是我的程序的要点:

我有一个名为 Person 的基类。它有一个叫President的孩子。我正在尝试在 President 类中创建一个“printInfo”函数,该函数从 both classes 打印其所有属性。

最简单的更改是通过更改名称来简单地区分功能,但我想知道是否有一种方法可以在不更改它们的情况下做到这一点。

(下面的代码只包含了相关部分,为了便于阅读,我省略了一堆其他的成员函数)


class Person : public Address {
public:
    void printInfo(); // this prints the name and birthday
private:
    string fname, lname, sex;
    int month, day, year;
};

class President : public Person {
private:
    int term;
public:
    void printInfo(); // this prints term
};

void President::printInfo() {
    cout << term << "  :  ";
    this->printInfo(); //need this to use the person version of itself
};

我想要什么:

1 : George Washington ....

实际结果:

1 : 1 : 1 : ....

【问题讨论】:

    标签: c++ oop object this


    【解决方案1】:

    可以通过添加Person::前缀来调用基类的成员函数。例如

    void President::printInfo() {
        cout << term << "  :  ";
        Person::printInfo();
    };
    

    顺便说一句:最好把printInfoPerson的析构函数做成virtual

    【讨论】:

      最近更新 更多