一、对象类重载 输出操作符 "<<" 和 输入操作符 ">>" 实现对象输出、输入
(参考链接:https://
www.cnblogs.com/yangguang-it/p/6489550.html)
#include "stdafx.h" #include <iostream> using namespace std; /* 遇到的问题:如何输出对象? 思考:C++中没有像Java中能使对象实现重载toString()的方法。 解决:C++中可以使对象类重载输出操作符,进而实现相同功能。 */ class Test { private: int a; int b; public: Test(int a = 0, int b = 0) { this->a = a; this->b = b; } //友元函数实现 输出 << 操作符 friend ostream & operator << (ostream &out, Test *obj) { out << obj->a << " " << obj->b; return out; } //友元函数实现 输入 >> 操作符 friend istream & operator >> (istream &in, Test *obj) { in >> obj->a >> obj->b; if (!in) { obj = new Test(); } return in; } }; int main() { Test *t1 = new Test(1, 2); int a = 1; //1.输出测试 cout << t1 << a << endl; //t1 和 a 的输出,调用了不同的输出函数 cout << "请输入两个int属性:"; //2.输入测试 cin >> t1; cout << t1 << endl; return 0; }
另附上 加减乘除 操作符的重载实现连接: