// << >> 运算符重载 写成全局函数 // cin cout 对应类型 istream ostream // cout << classA << endl; #include <iostream> using namespace std; class myClass { public: int m_c; int m_d; myClass(int a, int b):m_a(a), m_b(b) {}; void set_number(int a, int b){ this->m_c = a; this->m_d = b;} // friend ostream& operator<<(ostream& out, myClass my); // 友元函数 访问私有成员 private: int m_a; int m_b; }; ostream& operator<<(ostream& out, myClass my) { out << "c:" << my.m_c << " d:" << my.m_d << endl; // out << "a:" << my.m_a << "d:" << my.m_b << endl; // 私有成员 函数要作为友元函数 return out; } istream& operator>>(istream& in, myClass& my) // 需要修改my的内容 引用传参 { in >> my.m_c >> my.m_d; return in; } int main() { myClass my(1,1); my.set_number(12,34); cin >> my; cout << my << endl; return 0; }
原文:https://www.cnblogs.com/didiaoxiaoguai/p/14852044.html