为什么在下面的代码返回类型中是用于运营商重载的类类型
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;
}
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返回的过载
相关文章:
- 呼叫运营商<<临时
- 两个运营商的一些奇怪的冲突<<
- 如何在 CPP 中访问家长的运营商
- 如何明确调用好友流运营商
- 私有运营商删除会触发 GCC 和 Clang 的编译时错误,但不会在 MSVC 上触发编译时错误
- 使用运营商New分配的数据结构是否有任何副作用
- "Inheriting"移动运营商?
- 朋友ostream&运营商<<无法访问私人会员
- 为什么在下面的代码返回类型中是用于运营商重载的类类型
- 范围的枚举(枚举类)关系运营商
- 为什么“操作员”需要const但不是为“运营商&lt;”
- 对这两个分配运营商之间的不同感到困惑
- 我的班级意外加法运营商
- OpenACC - C++"新"运营商问题
- c 对运营商的一致性是新的,有多少重要
- 为什么我不能使私人运营商成为新的并使用默认实现?
- 全球取代所有新运营商
- 包装C 朋友在Cython中的非会员运营商
- 合法的交换运营商的模板实施
- 朋友超载的派生类和基本成员访问的运营商