【C++学习笔记】 3-2 类型转换构造函数


1. 类型转换构造函数


1.1 目的


实现类型的自动转换


1.2 特点


  • 只有一个参数
  • 不是复制构造函数

1.3 编译器自动调用


编译系统会自动调用 -> 转换构造函数
建立一个 临时对象 / 临时变量


2. 实例


class Complex{
	public:
		double real, imag;
		Complex(int i){//类型转换构造函数
			cout<<"IntConstructor called"<<endl;
			real = i; 
			imag = 0;
		}
		Complex(double r, double i)
		{
			real = r;
			imag = i;
		}
};
int main(){
	Complex c1(7, 8);
	Complex c2 = 12;
	c1 = 9; //9被自动转换成一个临时Complex对象
	cout<<c1.real<<","<<c1.imag<<endl;
	return 0;
}

输出:

IntConstructor called
IntConstructor called
9,0


站在巨人的肩上
【1】北京大学信息技术学院《程序设计实习》

猜你喜欢

转载自blog.csdn.net/Allen_Spring/article/details/106909952