其他分享
首页 > 其他分享> > explicit 易错

explicit 易错

作者:互联网

#include <iostream>
using namespace std;

class Fraction
{
    int m_numerator,m_denominator;
public:
    Fraction(int num,int den=1)
    : m_numerator(num) , m_denominator(den)  {}
    operator double() const {
        return (double)(m_numerator/m_denominator);
    }
    Fraction operator + (const Fraction& f){
        return Fraction(f);
    }
};
int main()
{
    Fraction f(3,2); 
    Fraction d2=f+4;
    cout << f << endl;
    cout << d2 << endl;
    return 0;
}

此种做法有二义性,编译不通过,Error:ambiguous

f可以转为double和4相加 再转为Fraction。也可以4转为Fraction在与f相加。

当加了 explicit关键字后

#include <iostream>
using namespace std;

class Fraction
{
    int m_numerator,m_denominator;
public:
    explicit Fraction(int num,int den=1)
    : m_numerator(num) , m_denominator(den)  {}
    operator double() const {
        return (double)(m_numerator/m_denominator);
    }
    Fraction operator + (const Fraction& f){
        return Fraction(f);
    }
};
int main()
{
    Fraction f(3,2); 
    Fraction d2=f+4;
    cout << f << endl;
    cout << d2 << endl;
    return 0;
}

此时编译也无法通过,加了explicit禁止了隐式构造函数的转化功能,所以4无法转化为Fraction类型 与 f 相加。但此时 f 会转化为 double与4相加,但explicit后 Fraction d2 = 4属于隐式定义无法通过编译

 

标签:易错,numerator,int,double,denominator,explicit,Fraction
来源: https://www.cnblogs.com/Mrsdwang/p/14321561.html