C++中如何在派生类重载<<运算符以打印全部属性
解决方案
问题的核心是全局重载的operator<<不支持多态——当你通过Parent*指针解引用得到Parent&时,编译器只会调用基类版本的operator<<,不会触发子类的重载。要实现多态打印,我们需要借助虚成员函数来实现动态绑定。
具体修改步骤:
- 在基类
Parent中定义一个虚打印函数,子类Child重写该函数 - 将全局的
operator<<简化,只调用这个虚打印函数,利用多态特性自动匹配对应类的打印逻辑 - 修正代码中存在的语法错误(比如参数名不匹配、未定义变量、容器类型错误等)
修正后的完整代码
#include <iostream> #include <vector> #include <string> using namespace std; class Parent{ public: Parent(string name, int age) : name(std::move(name)), age(age) {} // 定义虚打印函数,子类可重写 virtual void print(ostream& out) const { out << "Name: " << name << ", Age: " << age << "." << endl; } string& getName(){ return name; } int& getAge(){ return age; } protected: string name; int age; }; // 全局operator<<,调用虚函数实现多态 ostream& operator<<(ostream& out, const Parent& parent){ parent.print(out); return out; } class Child : public Parent{ public: Child(string name, int age, string school) : Parent(std::move(name), age), school(std::move(school)) {} // 重写父类的虚打印函数 void print(ostream& out) const override { // 先调用父类的打印逻辑输出name和age Parent::print(out); // 再追加子类独有的school属性 out << " School: " << school << endl; // 或者合并成一行: // out << "Name: " << name << ", Age: " << age << ", School: " << school << "." << endl; } private: string school; }; int main(){ vector<Parent*> v; v.push_back(new Parent("Father", 30)); v.push_back(new Child("Child", 10, "Sunny School")); for(auto ptr : v){ cout << *ptr; } // 记得释放内存,避免泄漏 for(auto ptr : v){ delete ptr; } v.clear(); return 0; }
代码说明:
- 将
Parent的成员变量改为protected,让子类可以直接访问(或者你也可以保留private,通过getName()/getAge()获取属性) - 虚函数
print标记为const,因为打印操作不应该修改对象状态 Child的print函数用override关键字显式标记重写,避免拼写错误- 全局
operator<<只需要接收const Parent&,内部调用print函数,此时会根据实际对象类型动态调用对应的版本 - 修正了原代码中的语法错误:比如
Parent类中operator<<的参数名saida和内部使用的out不匹配、main中vector<Father*>应为vector<Parent*>、Child类中未定义的type变量等
运行输出(分两行打印):
Name: Father, Age: 30. Name: Child, Age: 10. School: Sunny School
如果你希望把子类的属性和父类属性打印在同一行,可以修改Child::print为:
void print(ostream& out) const override { out << "Name: " << name << ", Age: " << age << ", School: " << school << "." << endl; }
此时输出会变成:
Name: Father, Age: 30. Name: Child, Age: 10, School: Sunny School.
内容的提问来源于stack exchange,提问作者Bernardo
相关产品推荐
相关产品推荐

