【C++编程】重载运算

重载运算符

重载调用调用运算符

#include <iostream>

struct absInt {
    int operator() (int val) const {
      return val < 0 ? -val : val;
    }
};

int main() {
  int i = -42;
  absInt obj;
  std::cout << obj(i) <<  std::endl; // 42
  return 0;
}

重载类型转换

#include <iostream>

class Complex {
  double real, imag;
public:
  Complex(double r = 0, double i = 0) :real(r), imag(i) {};
  operator double() { return real; }  //重载强制类型转换运算符 double
};

int main()
{
  Complex c(1.2, 3.4);
  cout << (double)c << endl;  //输出 1.2
  double n = 2 + c;  //等价于 double n = 2 + c. operator double()
  cout << n;  //输出 3.2
}

 

posted @ 2020-10-17 10:44  苏格拉底的落泪  阅读(152)  评论(0编辑  收藏  举报