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

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

  • 相关阅读:
    直线型一阶倒立摆5---硬件平台搭建
    PE view---重要参数--C语言实现
    A1132. Cut Integer
    A1131. Subway Map (30)
    A1130. Infix Expression
    A1129. Recommendation System
    A1128. N Queens Puzzle
    A1127. ZigZagging on a Tree
    A1126. Eulerian Path
    A1125. Chain the Ropes
  • 原文地址:https://www.cnblogs.com/Codroc/p/13998409.html
Copyright © 2011-2022 走看看