简体   繁体   English

为后缀重载一元运算符

[英]overloading a unary operator for postfix

Say I have a class as such 说我有一个班级

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

Now I can use it as such 现在我可以这样使用

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

Now if I wanted to use the unary operator as postfix then according to this page 现在,如果我想将一元运算符用作后缀,则根据页面

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. 正如您在本例中所看到的,当我们重新定义一元增量(++)和减量( - )重载运算符的函数时,我们使用int作为后修复的伪参数。 You must remember that int isn't an integer, but just a dummy argument. 你必须记住int不是一个整数,而只是一个伪参数。 You can see it as a signal to the compiler to create the post-fix notation of the operator. 您可以将其视为向编译器创建运算符的后缀表示法的信号。

I am using + instead of ++ since both are unary operators 我使用的是+而不是++,因为它们都是一元运算符

I could do the following 我可以做以下事情

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

However this (postfix) does not work 但是,此(后缀)不起作用

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

Any suggestions/comments on this issue ? 有关此问题的任何建议/意见?

+ cannot be a postfix operator. +不能是后缀运算符。 Only ++ and -- can. 只有++--可以。

C++ does not allow you to add new operators. C ++不允许您添加新的运算符。 You can only overload existing ones. 您只能超载现有的。 There is no postfix + operator in the language, so you cannot add it. 该语言没有后缀+运算符,因此您无法添加它。 You can overload prefix ++ and postfix ++ , because they both exist. 你可以重载前缀++和后缀++ ,因为它们都存在。

There's no such thing as a postfix + operator, this user-defined conversion: 用户定义的转换没有后缀+运算符之类的东西:

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

has an ' int ' parameter not by chance, try to write: 有一个' int '参数不是偶然的,尝试写:

foo d;
std::cout << (d+3) ; // No longer an "expression required" error

A recommended reading is §5.3.1/Unary operators 建议的读数是§5.3.1/一元运算符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM