I've implemented an Integer class with overloaded NOT operator as the following:
我用重载的NOT运算符实现了一个Integer类,如下所示:
#ifndef INTEGER_H
#define INTEGET_H
template <typename T>
T factorial(T t)
{
if (t == 1)
return 1;
return t * factorial(t - 1);
}
class Integer
{
private:
int value;
public:
Integer(int v) : value{v} {};
int getValue() const
{
return value;
}
void operator!()
{
value = factorial(value);
}
};
#endif
And it works if I call it before the typename as the following:
如果我在TypeName之前调用它,如下所示,它就会起作用:
#include <iostream>
#include "Integer.h"
using namespace std;
int main()
{
Integer i{5};
!i;
cout << i.getValue() << endl;
}
I want to have the operator on the right side of the typename not on the left side (i! not !i). Is this possible? If so, then how?
我希望运算符位于TypeName的右侧,而不是左侧(i!不是!i)。这个是可能的吗?如果是,那又是如何做到的呢?
更多回答
No, this is not possible in C++.
不,这在C++中是不可能的。
Because there is no postfix !
operator in C++. Operator overloading cannot invent new operators in C++, they can only, well, overload the existing ones.
因为没有后缀!C++中的运算符。运算符重载不能在C++中发明新的运算符,它们只能重载现有的运算符。
Operator overload choices for the unary operator on the right side: i++
and i--
. That is all.
右侧一元运算符的运算符重载选项:i++和i--。仅此而已。
优秀答案推荐
I want to have the operator on the right side of the typename not on the left side (i! not !i). Is this possible?
No, it isn't. The position of operands of operators is fixed by the language grammar and can't be customized and there is no post-fix !
operator in it. Also, I assume you mean "operand" instead of "typename", which doesn't make sense in that context since there is no type name in !i
.
不,不是。运算符的操作数的位置是由语言语法固定的,不能定制,也没有后缀!操作员在里面。另外,我假设您指的是“操作数”而不是“类型名”,这在该上下文中没有意义,因为!i中没有类型名。
Also, overloading !
like this is not a good idea. It will confuse everyone reading your code. Not only do you change the meaning of !
from being a logical negation to something else, but you also make it so that !
modifies its operand which normal logical operators will never do and also doesn't match the expectation of a mathematical operator.
还有,超载!好像这不是个好主意。这会让所有阅读您的代码的人感到困惑。你不仅改变了它的意思!从逻辑上的否定到其他的东西,但你也让它变得如此!修改它的操作数,这是正常的逻辑运算符永远不会做的,也不符合数学运算符的预期。
更多回答
Yes. I meant the variable name (x) which is the operand. Sorry about that. Thank you for your explanation. Now I know why there's no postfix negation operator available.
是。我指的是变量名(X),它是操作数。真对不起。谢谢你的解释。现在我知道为什么没有可用的后缀否定运算符了。
我是一名优秀的程序员,十分优秀!