新睿云

> 知识库 > explicit在C++中的相关用法

explicit在C++中的相关用法

作者/来源:新睿云小编 发布时间:2019-12-24

预测以下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

就像在GFact中所讨论的那样,在C ++中,如果类具有可以用单个参数调用的构造函数,则该构造函数将成为转换构造函数,因为这样的构造函数允许将单个参数转换为正在构造的类。

我们可以避免这种隐式转换,因为它们可能导致意外的结果。我们可以在explicit keyword的帮助下使构造函数显式。 例如,如果尝试下面的程序使用带有构造函数的显式关键字,则会出现编译错误。

#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 

热门标签
new year
在线咨询
咨询热线 400-1515-720
投诉与建议
{{item.description}}

—您的烦恼我们已经收到—

我们会将处理结果发送至您的手机

请耐心等待