explicit for ctors taking more than one argument

explicit for ctors taking more than one argument

struct Complex{
	double _real;
	double _i;
	Complex(double real, double i = 0) : _real(real), _i(i){} // ctor
	Complex operator+(const Complex &c){
		return Complex(c._real + _real, c._i + _i);
	}
	~Complex()=default;
};
int main(){
	Complex c1{4, 2};
	Complex c2 = c1 + 5; // 1
	return 0;
}

在这种情况下编译不会出现问题,为什么?等式 1 是调用了重载过的操作符 + ,但是参数传的是一个 Complex 和 一个 int,编译器会隐式地调用构造函数来构造一个 Complex(5) ,又由于存在这样地构造函数(因为虚数是有默认值的),所以等式 1 能被正确编译。

那么如果我在构造函数 ctor 前声明必须显式调用呢(explicit)

struct Complex{
	double _real;
	double _i;
    explicit  // !!!!!!!!!!!!!!!!!!!!
	Complex(double real, double i = 0) : _real(real), _i(i){} // ctor
	Complex operator+(const Complex &c){
		return Complex(c._real + _real, c._i + _i);
	}
	~Complex()=default;
};
int main(){
	Complex c1{4, 2};
	Complex c2 = c1 + 5; // 1
	return 0;
}

那么编译将无法通过!!!

posted @ 2020-11-19 16:00  Codroc  阅读(103)  评论(0编辑  收藏  举报