基于operator = copy重载和学习对象的赋值。编码运算符++的类。
说明如下:
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;
}
感谢。
答案 0 :(得分:1)
这与指定的行为不匹配,即增加调用对象operator++
的频率。
答案 1 :(得分:1)
operator++()
是预增量运算符。它旨在修改原始对象,然后在对象增加后返回对对象的引用。该引用允许代码直接从返回值继续访问原始对象,例如:
Seti s;
(++s).something // something applies to s itself, not a copy of s
operator++(int)
是后增量运算符。它旨在修改原始对象,然后在对象增加之前返回对象的副本。由于它返回对象的先前状态,因此它不会返回对原始对象的引用。
您的作业中显示的声明建议预增量运算符,因为没有输入参数。但是,返回值应该是一个参考。 正确的实现将是:
Seti& Seti::operator++()
{
if (this->freq < 9)
this->freq += 1;
return *this;
}
另一方面,如果您想实施后增量运算符,正确的实现将是:
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++