繁体   English   中英

为什么在下面的代码返回类型中将类类型用于运算符重载?

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

我一直在尝试了解运算符的重载,但没有在下面的程序中将返回类型用作类类型:当我用“ 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 如果过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转换。

观看演示

请注意,前缀和后缀递增/递减运算符的规范实现分别返回overload&overload

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

前置/后置增量运算符之间的区别在于,一个运算符可以直接对对象进行操作(前置增量:++ 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; 
}

暂无
暂无

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

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