0

基于 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;
}

谢谢。

4

2 回答 2

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++
于 2013-04-06T02:15:41.210 回答
1

这与指定的行为不匹配,即增加对象operator++被调用的频率。

于 2013-04-06T01:06:48.330 回答