• 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;
    }
    

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

  • 相关阅读:
    CNN做序列标注问题(tensorflow)
    对于梯度消失和梯度爆炸的理解
    LSTM(长短期记忆网络)及其tensorflow代码应用
    Python之禅
    Python namedtuple
    Linux里的2>&1
    PySpark笔记
    平衡二叉树,B树,B+树
    lzo文件操作
    Hadoop的Shell命令
  • 原文地址:https://www.cnblogs.com/Codroc/p/13998409.html
Copyright © 2020-2023  润新知