gpt4 book ai didi

c++ - 重载运算符++

转载 作者:太空狗 更新时间:2023-10-29 19:46:40 25 4
gpt4 key购买 nike

类声明:

class unaryOperators 
{
public:
int i;

unaryOperators (int tempI = 0)
{
i = tempI;
}

unaryOperators operator++ (int);
unaryOperators operator++ ();
};

这个全局定义是否对应重载运算符++的后缀或前缀版本?为什么?

unaryOperators operator++ (unaryOperators &one)
{
return one;
}

最佳答案

unaryOperators& operator++ (unaryOperators &one)
^^

是非成员前缀一元递增运算符。

非成员后缀一元递增运算符采用额外的 int 作为策略执行参数。

unaryOperators operator++ (unaryOperators &one, int)

引用:

C++03标准13.5.7自增自减[over.inc]

The user-defined function called operator++ implements the prefix and postfix ++ operator. If this function is a member function with no parameters, or a non-member function with one parameter of class or enumeration type, it defines the prefix increment operator ++ for objects of that type. If the function is a member function with one parameter (which shall be of type int) or a non-member function with two parameters (the second of which shall be of type int), it defines the postfix increment operator ++ for objects of that type. When the postfix increment is called as a result of using the ++ operator, the int argument will have value zero.125)

[Example:
class X {
public:
X& operator++(); // prefix ++a
X operator++(int); // postfix a++
};
class Y { };
Y& operator++(Y&); // prefix ++b
Y operator++(Y&, int); // postfix b++

void f(X a, Y b) {
++a; // a.operator++();
a++; // a.operator++(0);
++b; // operator++(b);
b++; // operator++(b, 0);
a.operator++(); // explicit call: like ++a;
a.operator++(0); // explicit call: like a++;
operator++(b); //explicit call: like ++b;
operator++(b, 0); // explicit call: like b++;
}
—end example]

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

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