【问题标题】:Why in below code return type is class type used for operator overloading?为什么在下面的代码中返回类型是用于运算符重载的类类型?
【发布时间】:2019-05-22 04:06:10
【问题描述】:

我一直在尝试理解运算符重载,但没有在以下程序中使用返回类型作为类类型: 当我用“int”切换“重载”返回类型时,它工作正常。

#include <iostream>
using namespace std; 

class overload { 
private: 
    int count; 

public: 
    overload(int i) 
        : count(i) 
    { 
    } 

    overload operator++(int) //why return type is class type when i can use int
    { 
        return (count++); 
    } 
    overload operator++() //why return type is class type when i can use int
    { 
            count = count + 1; 
            return count;        
    } 
    void Display() 
    { 
        cout << "Count: " << count<<endl; 
    } 
}; 
// Driver code 
int main() 
{ 
    overload i(5); 
    overload post(5); 
    overload pre(5); 

    // this calls "function overload operator ++()" function 
    pre = ++i; 
    post = i++; 
    i.Display(); 
    return 0; 
}

【问题讨论】:

  • 你想要它为什么工作/不工作,解释还是你只是想要让它正常工作的答案?
  • 它可以是int,但重载运算符的正常做法是按照人们期望的某种方式表现(返回与操作数相同的类型,并且返回正确的值类别为 pre -增量)。

标签: c++ operator-overloading


【解决方案1】:

前/后自增运算符之间的区别在于,它直接作用于对象(前自增:++foo),而需要获取对象的副本并返回(后自增:foo++)。写这个稍微冗长的方式是:

// return a new object that represents the old value
overload operator++(int)
{ 
    overload oldValue(count); // take copy
    count++;                  // increment this object
    return oldValue; 
} 

// increment the count, and return a reference to this object
overload& operator++()
{ 
    ++count;
    return *this;        
} 

虽然您可以返回 int (不要那样做!),但这只会导致混乱。实际上,它会导致一些代码问题,例如:

overload foo = ++someOtherFoo;

如果你要从 ++ 返回 int,最终会有效地调用你的构造函数(而不是复制构造函数)来构造一个新对象。即

overload foo = overload(++someOtherFoo);

那个构造函数可能不可用,所以代码会失败。

如果您希望您的对象自动将自身转换为整数,那么正确的方法是重载强制转换运算符,例如

operator int () const
{ 
  return count; 
}

【讨论】:

    【解决方案2】:

    对重载运算符的返回类型没有限制。这里也可以是int。 如果overload 类的构造函数被标记为explicit,则您显示的代码将类类型作为返回类型以方便代码中的其他语句,如下所示;

    例如:

    explicit overload(int i) 
            : count(i) 
    { 
    } 
    

    int operator++(int) //return type is  int
    { 
        return (count++); 
    } 
    int operator++() //return type is int
    { 
         count = count + 1; 
         return count;        
    } 
    

    以下将无法编译:

    pre = ++i; //will not work
    post = i++; //will not work
    

    这是因为隐式复制赋值运算符将不再适用于从 intconst overload 的转换。

    Demo

    请注意,前缀和后缀递增/递减运算符的Canonical implementations 分别返回overload&amp;overload

    虽然预增/预减的规范形式返回引用,与任何运算符重载一样,返回类型是用户定义的;例如这些运算符的重载 std::atomic 按值返回

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 2017-03-01
      相关资源
      最近更新 更多