operator type(){
//TODO:
return data;
}
#include <iostream> using namespace std; //复数类 class Complex{ public: Complex(): m_real(0.0), m_imag(0.0){ } Complex(double real, double imag): m_real(real), m_imag(imag){ } public: friend ostream & operator<<(ostream &out, Complex &c); friend Complex operator+(const Complex &c1, const Complex &c2); operator double() const { return m_real; } //类型转换函数 private: double m_real; //实部 double m_imag; //虚部 }; //重载>>运算符 ostream & operator<<(ostream &out, Complex &c){ out << c.m_real <<" + "<< c.m_imag <<"i";; return out; } //重载+运算符 Complex operator+(const Complex &c1, const Complex &c2){ Complex c; c.m_real = c1.m_real + c2.m_real; c.m_imag = c1.m_imag + c2.m_imag; return c; } int main(){ Complex c1(24.6, 100); double f = c1; //相当于 double f = Complex::operator double(&c1); cout<<"f = "<<f<<endl; f = 12.5 + c1 + 6; //相当于 f = 12.5 + Complex::operator double(&c1) + 6; cout<<"f = "<<f<<endl; int n = Complex(43.2, 9.3); //先转换为 double,再转换为 int cout<<"n = "<<n<<endl; return 0; }运行结果:
operator double() const { return m_real; } //转换为double类型 operator int() const { return (int)m_real; } //转换为int类型那么下面的写法就会引发二义性:
Complex c1(24.6, 100); float f = 12.5 + c1;编译器可以调用 operator double() 将 c1 转换为 double 类型,也可以调用 operator int() 将 c1 转换为 int 类型,这两种类型都可以跟 12.5 进行加法运算,并且从 Complex 转换为 double 与从 Complex 转化为 int 是平级的,没有谁的优先级更高,所以这个时候编译器就不知道该调用哪个函数了,干脆抛出一个二义性错误,让用户解决。
本文链接:http://task.lmcjl.com/news/8762.html