具有多个参数和符号的运算符重载

Operator overloading with multiple parameters and symbol

本文关键字:符号 运算符 重载 参数      更新时间:2023-10-16

我有一个类:

class taphop
{
    public:
        taphop();
        ~taphop();   
        taphop(const list&);
        taphop& operator=(const taphop&);
        taphop operator+(const int&);
        taphop operator+(const taphop&);
};

main中,我不能使用多个参数:

main()
{
     taphop lmc=lmc+2+5+3+2; // Error;
     lmc=lmc+3+5+2; // Error;
     int a=a+1+2+4+5;   // Not error;
     a=a+1+2+4+5;   // Not error;
     return 0;
}

有一点是肯定的。以下未定义。

taphop lmc=lmc+2+5+3+2;

由于运算符+将被调用在表达式中假定为完全构造对象的框架上

lmc+2+5+3+2

除了使用lmc初始化lmc之外,您只需要读取编译器给您的错误消息。以下是我对你可能试图做的事情的看法:

class taphop
{
    int value;
public:
    taphop(const int x = 0) :value(x) {} // default value of 0
    ~taphop() {}
    int getvalue() const { return value; }
    taphop& operator=(const taphop &r) { value = r.value; return *this; }
    taphop operator+(const int x) { return taphop(value + x); }
    taphop operator+(const taphop &r) { return taphop(value + r.value); }
};
int main()
{
    taphop lmc = taphop(0) + 2 + 5 + 3 + 2;
    std::cout << lmc.getvalue() << std::endl; // prints 12
    lmc = lmc + 3 + 5 + 2;
    std::cout << lmc.getvalue() << std::endl; // prints 22
    return 0;
}