我们可以让类相加, 相减, 自加, 自减, 这些就需要对类的运算符进行重载.
我将重点依旧写在代码注释里, 方便一步步的看
#include <iostream> #include <cstdlib> #include <string> class T1 { public: T1(int m = 0) : i(m) { if (i < 0) i = -i; } operator int() const { return i; } private: int c; int i; }; //重载类型; class T2 { public: T2() = default; T2(int x1, std::string str1) : x(x1), str(str1) {} //重载 += 运算符; T2 operator+= (const T2 t2) { x += t2.x; str += t2.str; return *this; } //重载 + 运算符; T2 operator+ (const T2 &t2) { *this += t2; //调用 += ; return *this; } //声明 - 运算符; T2 operator- (const T2 t2); //相等 == , 定义 == 就应该定义 != ; bool operator== (const T2 &t2) { return t2.x == x && t2.str == str; } bool operator!= (const T2 &t2) { return !(*this == t2); } void Print() { std::cout << x << " " << str << '\n'; } private: int x; std::string str; //声明 + T2 与 int 类型的运算符, 采用友元关系; friend T2 operator+ (T2 &t2, const int m); }; // + T2 与 int 类型的运算符; T2 operator+ ( T2 &t2, const int m) { t2.x += m; return t2; } // - 运算符; T2 T2::operator- (const T2 t2) { x -= t2.x; return *this; } class T3 { public: T3() = default; T3(int X, int Y, std::string str1) : x(X), y(Y), str(str1) {} //重载 []; //在 int 后加上引用 & 这样返回的是变量, 而不是常数值, 去掉或加上 const, 返回的值不能被修改; int& operator[] (const int m) { if (m == 0) return x; else if (m == 1) return y; } //自增, 前自增和后自增; //使用一个参数 (int) 来区分 前自增 还是 后自增; //后自增和自减返回的形式是一个值而非引用; T3& operator++ () //前自增; { ++x; ++y; return *this; } T3 operator++ (int) //后自增; { T3 t3 = *this; ++*this; return t3; } T3& operator-- () //前自减; { --x; --y; return *this; } T3 operator-- (int) //后自减; { T3 t3 = *this; --*this; return t3; } //重载(); T3& operator() () { x = -x; y = -y; return *this; } private: int x; int y; std::string str; }; int main() { T1 t1(1); //调用T1()默认构造函数; t1 = 4.3; //调用T1()默认构造函数; t1 + 3; //调用operator; std::cout << t1 << "\n"; //输出 4 ; T2 t2(1, "a"), t_2(2, "b"); //调用 T2 + T2; std::cout << "调用 T2 + T2; "; t_2 = t_2 + t2; //调用operator进行相加; //t_2.operator+=(t2);显示调用; t_2.Print(); //输出3, ba; //调用 T2 - T2; std::cout << "调用 T2 - T2; "; t_2 = t_2 - t2; t_2.Print(); //输出 1, ba; //调用 T2 + int; //未定义 int + T2, 所以 4 + t2 是错误的; std::cout << "调用 T2 + int "; t2 = t2 + 4; t2.Print(); //输出5, a; //调用 == 与 != std::cout << "调用 == 与 != "; //t2.operator==(t_2); std::cout << (t2 == t_2) << "\n"; T3 t3(1, 2, "abc"); //角标; std::cout << "角标; "; int i = t3[1]; t3[0] = 4; //t3.operator[](0); std::cout << t3[0] << " " << i << std::endl; //调用自增; std::cout << "调用自增; "; t3++; ++t3; //t3.operator++(0);//显示调用 //t3.operator++(); std::cout << t3[0] << " " << t3[1] << std::endl; system("pause"); return 0; }