可以重載輸出流運算符 <<
來實現。具體實現如下:
#include<iostream>
using namespace std;
class Person{
public:
int age;
string name;
friend ostream& operator<<(ostream& out, const Person& p){
out << "name: " << p.name << " age: " << p.age;
return out;
}
};
class Student{
public:
int id;
Person person;
friend ostream& operator<<(ostream& out, const Student& s){
out << "id: " << s.id << " person: " << s.person;
return out;
}
};
int main(){
Person p;
p.age = 20;
p.name = "Tom";
Student s;
s.id = 1;
s.person = p;
cout << s << endl; //輸出: id: 1 person: name: Tom age: 20
return 0;
}
在上述代碼中,Person
類重載了 <<
運算符,將姓名和年齡輸出。Student
類重載了 <<
運算符,將學號和 Person
對象輸出,這樣在輸出 Student
對象時就可以輸出所有信息了。