gpt4 book ai didi

c++ - 为后缀重载一元运算符

转载 作者:搜寻专家 更新时间:2023-10-30 23:57:07 24 4
gpt4 key购买 nike

假设我有一个类

class foo
{
public:
char* operator+ () //unary operator - prefix before instance
{
return "SomeChar";
}
};

现在我可以这样使用它了

foo d;
std::cout << +d; //unary operator used as prefix allowed

现在如果我想使用一元运算符作为后缀,那么根据 this

As you can see in this case we use int as a dummy argument for post-fix, when we redefine the functions for the unary increment (++) and decrement (--) overloaded operators. You must remember that int isn't an integer, but just a dummy argument. You can see it as a signal to the compiler to create the post-fix notation of the operator.

我使用 + 而不是++,因为它们都是一元运算符

我可以做以下事情

class foo
{
public:
char* operator+ () //unary operator - prefix before instance
{
return "SomeChar";
}

//Added this for postfix unary operation
char* operator+ (int) //unary operator - postfix before instance
{
return "SomeChar";
}
};

但是这个(后缀)不起作用

foo d;
std::cout << (d+) ; //unary operator used as post fix ERROR (Expected an expression)

关于这个问题有什么建议/意见吗?

最佳答案

C++ 不允许您添加 新的运算符。您只能重载 现有的。该语言中没有后缀 + 运算符,因此您无法添加它。您可以重载前缀 ++ 和后缀 ++,因为它们都存在。

关于c++ - 为后缀重载一元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26011981/

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