Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在c++; 是否可以重载二进制运算符,只在C++中使用一个操作数?< /P>_C++_Operator Overloading - Fatal编程技术网

在c++; 是否可以重载二进制运算符,只在C++中使用一个操作数?< /P>

在c++; 是否可以重载二进制运算符,只在C++中使用一个操作数?< /P>,c++,operator-overloading,C++,Operator Overloading,我尝试用一个类似的类来实现这一点: #include <iostream> using namespace std; class IntWrap { public: IntWrap operator=(int rhs) { val = rhs; return *this; } // No second operand for + IntWrap operator+() { IntWrap resul

我尝试用一个类似的类来实现这一点:

#include <iostream>

using namespace std;

class IntWrap {
public:
    IntWrap operator=(int rhs) {
        val = rhs;
        return *this;
    }

    // No second operand for +
    IntWrap operator+() {
        IntWrap result;
        result = val + 1;
        return result;
    }

    int Val() {return val;}

private:
    int val;
};
成员函数可以与
test.operator+()
一起使用,但实际上并不使用操作符

<> > St>更具体地说,重载二进制操作符,只有C++操作所允许的一个操作数吗?如果是这样的话,是否可以使用运算符表示法调用重载函数,也可以对右侧操作数使用某种伪值?


另外,别担心,我不打算在任何真正的代码中使用它,我只是好奇,因为我找不到关于它的任何东西。

您不是重载二进制运算符,而是重载一元运算符+。正确的用法是

IntWrap test;
test = 0;
+test;

您不是在重载二进制运算符,而是在重载
一元运算符+
运算符。正确的用法是

IntWrap test;
test = 0;
+test;
N4140[over.oper]/6:

无法更改运算符的优先级、分组、或操作数

在代码中,您重载了一元
+
运算符,而不是二进制运算符。

N4140[over.oper]/6:

无法更改运算符的优先级、分组、或操作数

在代码中,您重载了一元
+
运算符,而不是二进制运算符

是否可以重载二进制运算符,只在C++中使用一个操作数?< /P> 不,你不能那样做。运算符重载不允许更改语言的语法或运算符优先级。它只允许您更改使用操作员时发生的情况

你做了什么

IntWrap operator+() { ... }
重载一元
+
运算符

您应该能够使用:

IntWrap test;
test = 0;
+test;

是否可以重载二进制运算符,只在C++中使用一个操作数?< /P> 不,你不能那样做。运算符重载不允许更改语言的语法或运算符优先级。它只允许您更改使用操作员时发生的情况

你做了什么

IntWrap operator+() { ... }
重载一元
+
运算符

您应该能够使用:

IntWrap test;
test = 0;
+test;
二元运算符(成员函数)接受单个参数(第一个是对象),而独立运算符需要两个二元运算符(成员函数)接受单个参数(第一个是对象),而独立运算符需要两个