重载类型转换运算符

class Complex{
    
    
    double real, imag;
    public:
    Complex(double r=0,double i=0):real(r),imag(i){
    
    }
    operator double (){
    
    //重载强制类型转换运算符函数的返回值是不用写的,默认是类型本身
        return real;
    }
};
int main() {
    
    
    Complex c(1.2, 3.4);
    cout << (double)c << endl;
    double n = 2 + c; //等价于2+c.operator double();
    cout << n << endl;
    return 0;
}
######  输出
```c
1.2
3.2

猜你喜欢

转载自blog.csdn.net/weixin_43311695/article/details/106701169