基于operator=复制重载和学习对象的赋值。为类编写operator++代码。
具体操作步骤如下:
Seti operator++( );
This operator simply increases the value of a Seti object's frequency
by 1 (to a maximum of 9), before returning a copy of itself.
NOTE: The frequency can never exceed 9.我可以这样做吗:
Seti Seti::operator++( ) {
Seti temp;
temp = *this
if (temp.freq<9)
temp.freq+=1;
return temp;
}谢谢。
发布于 2013-04-06 09:06:48
这与指定的行为不匹配,指定的行为是增加调用对象operator++的频率。
发布于 2013-04-06 10:15:41
operator++()是前增量运算符。它的目的是修改原始对象,然后在对象被递增后返回对该对象的引用。引用允许代码继续直接从返回值访问原始对象,例如:
Seti s;
(++s).something // something applies to s itself, not a copy of spost-increment运算符是operator++(int)。它的目的是修改原始对象,然后在对象被递增之前返回对象的副本。因为它返回对象的先前状态,所以它不返回对原始对象的引用。
赋值中显示的声明建议使用前增量运算符,因为没有输入参数。但是,返回值应该是一个引用。正确的实现应该是:
Seti& Seti::operator++()
{
if (this->freq < 9)
this->freq += 1;
return *this;
}另一方面,如果您想实现post-increment运算符,正确的实现应该是:
Seti Seti::operator++(int)
{
Seti temp(*this);
if (this->freq < 9)
this->freq += 1;
return temp;
}使用运算符时:
Seti s;
++s; // calls operator++()
s++; // calls operator++(int)C++标准的13.5.7节显示了这些运算符的官方声明:
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++https://stackoverflow.com/questions/15845872
复制相似问题