C++学习笔记:构造函数与隐式转换
程序设计课时老师给出了关于构造函数与类型隐式转换的一个例子:
设对以下复数类:
#include<iostream>
using namespace std;
class Complex {
public:
Complex(int a = 0, int b = 0): real(a), imag(b) {}
Complex operator+(const Complex &other) {
Complex tmp;
tmp.imag=imag+other.imag;
tmp.real=real+other.real;
return tmp;
}
int get_real(){
return real;
}
int get_imag(){
return imag;
}
private:
int real;
int imag;
};
int main(){
Complex a(1,2);
Complex b(3);
Complex sum1,sum2;
sum1=a+b;
sum2=a+2;
cout<<sum1.get_real()<<" "<<sum1.get_imag()<<endl;
cout<<sum2.get_real()<<" "<<sum2.get_imag()<<endl;
}
在DevC++中编译通过,输出为:
4 2
3 2
但是,我们在类的定义中所定义的Complex operator+(const Complex &other),该函数需要传入的参数应该是一个Complex类, 代码sum2=a+2应该不能运行,因为他传入的是一个int参数。
而该代码可以编译通过并得到正确答案的原因在于:在运行 sum2=a+2;这段代码时,发生了隐式转换,即调用了构造函数将int形对象2转换为了Complex类,之后再进行运算。能调用构造函数的原因是该构造函数已经为real和imag提供了默认值,故只传入一个参数2,也可以调用构造函数Complex(int a = 0, int b = 0): real(a), imag(b) {};
若将构造函数改为以下形式:
Complex():real(0),imag(0){}
Complex(int a , int b ): real(a), imag(b) {}
//下方对b的初始化也需改为Complex b(3,0)
此时再运行程序,sum2=a+2处会报错:no match for ‘operator+’ (operand types are ‘Complex’ and ‘int’); 是因为此时没有相应的函数可以隐式的把2转化成Complex类了。
版权声明:本文为qq_45779361原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。