zoukankan      html  css  js  c++  java
  • 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;
    }
    

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

  • 相关阅读:
    [树形DP]Luogu P1131 [ZJOI2007]时态同步
    [状压DP]JZOJ 1303 骑士
    [DFS]JZOJ 1301 treecut
    [最小费用最大流]JZOJ 4802 探险计划
    [KMP][倍增求LCA]JZOJ 4669 弄提纲
    [DP]JZOJ 1758 过河
    列表生成式和生成器表达式
    协程函数
    生成器
    迭代器
  • 原文地址:https://www.cnblogs.com/Codroc/p/13998409.html
Copyright © 2011-2022 走看看