最新消息:阿里云双12优惠,史上最低折扣。

explicit在C++中的相关用法

服务器租用 aliyun 182浏览

云服务模式IaaS基础设施即服务

云计算中有三种服务模式,分别是:基础设施即服务(IasS)、平台即服务(PasS)、软件即服务(SaaS)这几种模式,本文对基础设施即服务(IasS)进行了详尽的解析。

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

转载请注明:小猪云服务器租用推荐 » explicit在C++中的相关用法