#include <iostream>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string name, int age) {
this->name = name;
this->age = age;
}
~Person() {
cout<<"\nThe object of "<<name<<" has been deleted!";
}
//将<<运算符定义为Person类的友元函数后,
//编译系统自动将cout<<p解释为operator<<(cout, p)
friend ostream& operator<<(ostream& output, Person& p) {
output<<"Name:"<<p.name<<"\tAge:"<<p.age;
return output;
}
};
int main(int argc, char** argv) {
Person p("大明", 22);
cout<<p<<endl;
return 0;
}
C++重载“<<”,“>>”运算符与友元函数
于 2025-03-07 11:50:50 首次发布
1516

被折叠的 条评论
为什么被折叠?



