加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 重载运算符

发布时间:2020-12-16 10:21:01 所属栏目:百科 来源:网络整理
导读:舱位声明: class unaryOperators { public: int i; unaryOperators (int tempI = 0) { i = tempI; } unaryOperators operator++ (int); unaryOperators operator++ ();}; 此全局定义是否与重载运算符的后缀或前缀版本相对应?为什么? unaryOperators opera
舱位声明:

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]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读