#include<iostream>
#include<string>
using namespace std;

class person {
    friend ostream& operator<<(ostream& cout, person& p); //申明友元函数,让其权限可以使用私有成员
private:
    int age;
    int height;
public:
    person(int a, int b) {
        age = a;
        height = b;
    }

};

//重载左移运算符
//必须是全局函数重载,因为局部会导致cout无法在左边

ostream& operator<<(ostream& cout, person& p) {  //cout在全局都"只能有一个",所以只能引用传参
    cout << "年龄是:" << p.age << "\t身高是:" << p.height;
    return cout;
};

int main() {
    person p1(10,100);
    cout << p1 << endl;
}

发表回复

后才能评论