类型转换函数 & 转换构造函数

转换构造函数

用途:将一个其它类型的数据转换成自定义的类类型。

注意:这种构造函数只有一个参数,但要区别于拷贝构造函数(形参是一个自定义类型的引用)

例子:


#include <iostream>

using namespace std;

class Complex
{
    public:
//      Complex():real(0), imag(0){}

        //这个缺省的构造函数便可以充当 转换构造函数
        Complex(double r=0, double i=0):real(r),imag(i){} 

//      Complex(double d):real(d), imag(0){
//          cout << "complex(double).." << endl;
//      }

        friend Complex operator+(const Complex &, const Complex &);

        friend ostream &operator<<(ostream &out, Complex &t);

    private:
        double real;
        double imag;
};

ostream &operator<<(ostream &out, Complex &c)
{
    out << "(complex: " << c.real << "," << c.imag << ")";

    return out;
}

Complex operator+(const Complex &c1, const Complex &c2)
{
    Complex temp;

    temp.real = c1.real + c2.real;
    temp.imag = c1.imag + c2.imag;

    return temp;
}

int main()
{
    Complex c1 = 3.14;
    Complex c2;
    c2 = 4.2;

    Complex c3 = c1 + c2;

    c3 = c1 + 0.5;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

类型转换函数

用途:将一个自定义类对象转换为int , double , float 以及其它类类型. 如:

    double b = 2.1;
    Complex(一个类名) c1;
    b = c1;

注意:这个函数需要声明成类的成员函数

仍然借用上面的类形式如下

operator 类型名()
{
    .....实现返回的语句 
}
    //加到上面的类中   
    operator double()
    {
        return real;  
    }

    int main()
    {
        double b;
        Complex c(1.2,1.3);

        //将对象c转换为一个double b = (real)1.2,此为隐式,
        b = c;   
        //b = c.operator double();此为显示,好怪异啊,除非将其声明为explicit, 否则系统默认为隐式

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

!! 当上面两种函数,以及与操作符重载函数一起使用时,容易歧义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值