C++:关键字explicit的用法

预测下面C++程序的输出:

#include <iostream> 

using namespace std; 

class Complex 
{ 
private: 
    double real; 
    double imag; 

public: 
    // Default constructor 
    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} 

    // A method to compare two Complex numbers 
    bool operator == (Complex rhs) { 
    return (real == rhs.real && imag == rhs.imag)? true : false; 
    } 
}; 

int main() 
{ 
    // a Complex object 
    Complex com1(3.0, 0.0); 

    if (com1 == 3.0) 
    cout << "Same"; 
    else
    cout << "Not Same"; 
    return 0; 
} 

输出:编译通过,产生输出。

Same

在C++中,如果一个类有一个可以用单个参数调用的构造函数,那么这个构造函数就变成了转换构造函数,因为这样的构造函数允许将单个参数转换成正在构造的类。 我们可以避免这种隐式转换,因为这可能会导致意想不到的结果。我们可以借助explicit使构造函数显式化。例如,如果我们尝试下面的程序,在构造函数中使用显式关键字,我们会得到编译错误。
#include <iostream> 

using namespace std; 

class Complex 
{ 
private: 
    double real; 
    double imag; 

public: 
    // Default constructor 
    explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} 

    // A method to compare two Complex numbers 
    bool operator== (Complex rhs) { 
    return (real == rhs.real && imag == rhs.imag)? true : false; 
    } 
}; 

int main() 
{ 
    // a Complex object 
    Complex com1(3.0, 0.0); 

    if (com1 == 3.0) 
    cout << "Same"; 
    else
    cout << "Not Same"; 
    return 0; 
} 

输出:编译错误。

no match for 'operator==' in 'com1 == 3.0e+0'

我们仍然可以将double类型转换为Complex类型,但是现在我们必须要明确对它进行类型转换。例如,下面这个程序就工作正常。

#include <iostream> 

using namespace std; 

class Complex 
{ 
private: 
    double real; 
    double imag; 

public: 
    // Default constructor 
    explicit Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} 

    // A method to compare two Complex numbers 
    bool operator== (Complex rhs) { 
    return (real == rhs.real && imag == rhs.imag)? true : false; 
    } 
}; 

int main() 
{ 
    // a Complex object 
    Complex com1(3.0, 0.0); 

    if (com1 == (Complex)3.0) 
    cout << "Same"; 
    else
    cout << "Not Same"; 
    return 0; 
} 

输出:编译通过,产生输出。

Same

 
 
原文地址:https://www.cnblogs.com/2018shawn/p/11465461.html