关于类中定义了转换函数并重载加法运算符,出现二义性报错的问题

问题遇到的现象和发生背景

定义了一个Star类,为了让它和int类可以无缝转换,定义了转换函数,和只有int类型参数的构造函数。如下代码,问题在代码后

问题相关代码,请勿粘贴截图
#include <iostream>
using namespace std;

class Star
{
private:
    int a;
public:
    Star() { a = 0; }
    Star(int l) { a = l;}
    operator int() { cout << "转换函数" << endl ;return a * 2; }
    void get() { cout << a << endl; }
    Star operator+(const Star& rs) {
        cout << "加法运算符" << endl;
        Star temp((rs.a + a)*2);
        return temp;
    }
};

int main(){
    Star a(1);
    Star b = a + 2;    // 问题坐标1
    a.get();
    b.get();
}


运行结果及报错内容

在没有重载加法运算符时,代码中问题坐标1处, 无论是b = a + 2 或 b = 2 + a,都是将a转换成int类型。我解释为,因为Star类没有加法运算,int类型有加法运算所以会执行转换函数,将Star转换为int

定义了重载运算符后,代码中问题坐标1处,
b = 2 + a:还是调用转换函数,将 a 转换成int类型,进行加法运算
问题来了:b = a + 2:出现二义性报错,按理说不是应该是 a 调用了 Star 类中重载的加法运算符,将2传了进去,然后2就被转换成Star类型,进行Star类的加法运算么。为什么会有二义性报错?


#include <iostream>
using namespace std;
class Star
{
private:
    int a;
public:
    Star() { a = 0; }
    Star(int l) { a = l; }
    operator int() { cout << "转换函数" << endl; return a * 2; }
    void get() { cout << a << endl; }
    Star operator+(const Star& rs) {
        cout << "加法运算符" << endl;
        Star temp((rs.a + a) * 2);
        return temp;
    }
};
int main() {
    Star a(1);
    Star c(2);

    Star b = a + c;    // 问题坐标1
    a.get();
    b.get();
}

Star 没返回值的话可以加吗 21行

编译器也可以先调用转换函数,将a转换成int类型,然后和2相加,最后调用构造函数构造出b。这和你说的想法不是两种选择吗?所以二义性。