您的位置:首页 > 其它

类型转换构造函数

2016-03-03 11:36 344 查看

目的:

实现类型的自动转换

特点:

只有一个参数

不是复制构造函数

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: