gpt4 book ai didi

c++ - 在 C++ 中为一个操作数重载二元运算符

转载 作者:行者123 更新时间:2023-11-30 01:48:35 26 4
gpt4 key购买 nike

能否在 C++ 中重载二元运算符以仅接受一个操作数?

我试着用一个类似这样的类来实现它:

#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;
};

这段代码竟然是用GCC编译的,这让我很惊讶,它甚至没有用-Wall给出任何警告

我遇到的问题实际上是使用重载运算符。

这不会编译,因为 GCC 需要在 + 之后有一个操作数:

int main() {
IntWrap test;
test = 0;

test +; // GCC expects an operand after +

return 0;
}

成员函数可以与 test.operator+() 一起使用,但实际上并没有使用运算符。

那么更具体地说,C++ 标准是否允许仅使用一个操作数重载二元运算符?如果是这样,是否可以使用运算符符号调用重载函数,可能是通过对右侧操作数使用某种虚拟值?

另外,别担心,我不打算在任何实际代码中使用它,我只是好奇,因为我找不到任何关于它的信息。

最佳答案

Can you overload a binary operator to take only one operand in C++?

不,你不能那样做。运算符重载不允许您更改语言的语法或运算符优先级。它只允许您更改使用运算符时发生的情况。

你做了什么

IntWrap operator+() { ... }

重载一元 + 运算符。

您应该能够使用:

IntWrap test;
test = 0;
+test;

关于c++ - 在 C++ 中为一个操作数重载二元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30311798/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com