c++ - 为什么我不能像 someClassObject++5 那样在后缀 operator++ 中使用虚拟参数?

标签 c++ operator-overloading

我知道我可以在后缀 operator++ 中使用虚拟 int 作为 someClassObject.operator++(5),但为什么不能像 someClassObject++5 那样使用它?我问这个是因为 operator+ 可以像 someClassObject1 + someClassObject2 一样使用。

{
public:

    test(int x, string y) : x(x), y(y){}
    test() :x(0), y("") {};

    //skiping some code for copy constructor and assignment operator overload

    test operator++(int x)
    {
        test a(*this);
        a.x += x;
        ++(*this);
        return a;
    }

    friend ostream& operator<<(ostream& ost, const test& test)
    {
        ost << test.x << " , " << test.y;
        return ost;
    }


    int x;
    string y;
};

int main()
{
    test t1(5, "testing");
    int x = 10;
    cout << t1.operator++(x) << endl;
    //the above line of code works but the line below gives error.
    t1++x;
    return 0;
}

我希望 t1.operator++(5)t1++5 都能以相同的方式工作。

最佳答案

由于最大咀嚼规则,表达式

t1++x

解析

t1 ++ x

分组

(t1 ++) x

这毫无意义;而像 t1 x 是没有意义的。

关于c++ - 为什么我不能像 someClassObject++5 那样在后缀 operator++ 中使用虚拟参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56440118/

相关文章:

java - C++ 与 Java 中函数重载的歧义

c++ - 模板类成员函数

c++ - 为什么这个 << 重载不编译

swift - 为 swift Range 类型创建自定义运算符

c++ - 为什么析构函数总是声明为虚拟的

c++:如何将字符串分解(不解析)为命令行参数?

c++ - 在嵌入式环境中使用 C++

c++ - 数组或 vector 中的元素改变C++

c++ - C++中运算符重载的返回值

c++ - 在 C++ 中重载 [] 运算符