类型转换构造函数

目的:

实现类型的自动转换

特点:

  • 只有一个参数
  • 不是复制构造函数
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
class complex{
    private:
        double real,imag;
    public:
        complex(int i)//类型转换构造函数 
        {
            cout<<"Intconstructor is called"<<endl;
            real=i;
            imag=0;
        }
        complex()
        {
        cout<<"no parameter constructor is called"<<endl;   
        }
        complex(double x,double y)
        {
        real=x;
        imag=y; 
        cout<<"constructor is called"<<endl;
        }
        complex(const complex&c)
        {
            real=c.real;
            imag=c.imag;
            cout<<"copy constuctor is called."<<endl;
        }
        void get_complex()
        {
        cout<<real<<"+"<<imag<<"i"<<endl;   
        }   
};
complex fun()
{
    complex a(1,2);
    return a;
}
int main()
{
    complex c1(7,8);
    complex c2=12;//初始化语句,直接调用complex(int)初始化c2 
    c1=9;//赋值语句,9被自动转化为一个临时的complex对象,然后将临时对象的值赋值给c1 
    c1.get_complex();
    return 0;
}

程序结果:

constructor is called
Intconstructor is called
Intconstructor is called
9+0i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值