这是我的程序的要点:
我有一个名为Person 的基类。它有一个名为 President 的 child 。我正在尝试在 President 类中创建一个“printInfo”函数,该函数打印它在两个类 中的所有属性。
最简单的改变是通过更改名称来简单地区分功能,但我想知道是否有一种方法可以在不更改名称的情况下做到这一点。
(下面的代码只包含相关部分,我省略了一堆其他成员函数以便于阅读)
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 : ....
最佳答案
可以通过添加Person::
前缀来调用基类的成员函数。例如
void President::printInfo() {
cout << term << " : ";
Person::printInfo();
};
顺便说一句:最好让 printInfo
和 Person
的析构函数 virtual
。
关于c++ - 如何使用父类的同名成员函数(通过 this->)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55719607/