转换构造函数

通常使用转换构造函数将一个指定的数据转换成类对象的方法是:
1、先声明一个类
2、在这个类中定义一个只有一个参数的构造函数,参数是待转换类型的数据,在函数体中指定转换的方法**

#include<iostream>
using namespace std;
class complex
{
    public:
        complex()
        {
        }
        complex(double r,double i)
        {
            real=r;
            imag=i;
        }
        complex(double r)//转换构造函数 
        {
            real=r;
            imag=0;
        }
        friend complex operator+(complex &col,complex &co2);
        void print();
        private:
            double real,imag;
 };

 complex operator+(complex &co1,complex &co2)
 {
    complex temp;
    temp.real=co1.real+co2.real;
    temp.imag=co1.imag+co2.imag;
    return temp;
 }

 void complex::print()
 {
    cout<<real;
    if(imag>0)
    {
        cout<<"+";
     }
     if(imag!=0)
     {
        cout<<imag<<"i"<<endl;
     }
  }

int main()
{
    complex com1(1.1,2.3),total;
    complex com2(7.6);//调用构造函数,将7.6转换成对象com2 
    total=com1+com2;
    total.print();
    return 0;
}

结果:
8.7+2.3i

类型转换函数
1、类型转换函数只能定义一个类的成员函数而不能定义为类的友元函数,类型转换类型也可以在类体中声明函数原型,而将函数体定义在类的外部
2、类型转换函数既没有参数,也不能在函数名前指定函数类型
3、类型函数中必须有return语句,必须送回目标类型的数据作为函数的返回值

#include<iostream>
using namespace std;
class complex
{
    public:
        complex(double r=0,double i=0)
        {
            real=r;
            imag=i;
        }
        operator double()//类型转换函数,complex类对象转换成double型数据 
        {
            return real;
        }
        operator int()// complex类对象转换成int型数据
        {
            return int(real);
        }
        private:
            double real,imag;
};

int main()
{
    complex com1(22.4,34.4);
    cout<<"complex类对象转换成double型数据为:";
    cout<<double(com1)<<endl;
    cout<<"complex类对象转换成int型数据为:";
    cout<<int(com1)<<endl;
    return 0;
}

结果:
complex类对象转换成double型数据为:22.4
complex类对象转换成int型数据为:22

#include<iostream>
using namespace std;
class complex
{
    public:
        complex()
        {

        }
        complex(int r,int i)
        {
            real=r;
            imag=i;
        }
        complex(int i)//转换构造函数,将int类型的数据转换成complex类的对象   (2)
        {
            real=imag=i/2;
        }
        operator int()//转换构造函数,将complex类型的数据转换成int类型的数据    (1)
        {
            return real+imag; 
        }
        void print()
        {
            cout<<"real:"<<real<<" imag:"<<imag<<endl;
        }

        private:
            int real,imag;
};
int main()
{
    complex a1(1,2),a2(3,4);//建立对象a1,a2,两次调用带参构造函数
    complex a3;//建立对象a3,调用不带参数的构造函数
    a3=a1+a2;//执行方法顺序(1)(2)
    a3.print();
    return 0;
}

结果:
real:5 imag:5

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值