为什么在下面的代码返回类型中是用于运营商重载的类类型

Why in below code return type is class type used for operator overloading?

本文关键字:运营商 重载 用于 类型 在下面 代码 返回类型 为什么      更新时间:2023-10-16

我一直在尝试了解操作员的过载,并且没有将返回类型用作以下程序中的类类型的使用:当我切换"超载"返回类型" 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; 
}

pre/post增量运算符之间的差异是直接在对象上工作(添加预告: 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; 
}

对超载运算符的返回类型没有限制。这里也可以是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

这是因为隐式副本分配运算符将不再可行,从int转换为const overload

请参阅 demo

请注意,前缀和后缀增量/减少操作员的规范实现分别返回overload&overload

尽管预先提前/预定的规范形式返回参考,就像任何操作员过载一样,返回类型是用户定义;例如,这些运算符的std :: Atomic返回的过载