语法格式

类型转换函数也没有参数,因为要将当前类的对象转换为其它类型,所以参数不言而喻

  1. operator type(){
  2. //TODO:
  3. return data;
  4. }

示例

将Complex类型转换为double

  1. #include <iostream>
  2. using namespace std;
  3. //复数类
  4. class Complex{
  5. public:
  6. Complex(): m_real(0.0), m_imag(0.0){ }
  7. Complex(double real, double imag): m_real(real), m_imag(imag){ }
  8. public:
  9. friend ostream & operator<<(ostream &out, Complex &c);
  10. friend Complex operator+(const Complex &c1, const Complex &c2);
  11. operator double() const { return m_real; } //类型转换函数
  12. private:
  13. double m_real; //实部
  14. double m_imag; //虚部
  15. };
  16. //重载>>运算符
  17. ostream & operator<<(ostream &out, Complex &c){
  18. out << c.m_real <<" + "<< c.m_imag <<"i";;
  19. return out;
  20. }
  21. //重载+运算符
  22. Complex operator+(const Complex &c1, const Complex &c2){
  23. Complex c;
  24. c.m_real = c1.m_real + c2.m_real;
  25. c.m_imag = c1.m_imag + c2.m_imag;
  26. return c;
  27. }
  28. int main(){
  29. Complex c1(24.6, 100);
  30. double f = c1; //相当于 double f = Complex::operator double(&c1);
  31. cout<<"f = "<<f<<endl;
  32. f = 12.5 + c1 + 6; //相当于 f = 12.5 + Complex::operator double(&c1) + 6;
  33. cout<<"f = "<<f<<endl;
  34. int n = Complex(43.2, 9.3); //先转换为 double,再转换为 int
  35. cout<<"n = "<<n<<endl;
  36. return 0;
  37. }