首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这个指针,operator=和operator++

这个指针,operator=和operator++
EN

Stack Overflow用户
提问于 2013-04-06 09:01:06
回答 2查看 120关注 0票数 0

基于operator=复制重载和学习对象的赋值。为类编写operator++代码。

具体操作步骤如下:

代码语言:javascript
复制
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.

我可以这样做吗:

代码语言:javascript
复制
Seti Seti::operator++( ) {
    Seti temp;
    temp = *this
    if (temp.freq<9)
    temp.freq+=1;
    return temp;
}

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2013-04-06 09:06:48

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

票数 1
EN

Stack Overflow用户

发布于 2013-04-06 10:15:41

operator++()前增量运算符。它的目的是修改原始对象,然后在对象被递增后返回对该对象的引用。引用允许代码继续直接从返回值访问原始对象,例如:

代码语言:javascript
复制
Seti s;
(++s).something // something applies to s itself, not a copy of s

post-increment运算符是operator++(int)。它的目的是修改原始对象,然后在对象被递增之前返回对象的副本。因为它返回对象的先前状态,所以它不返回对原始对象的引用。

赋值中显示的声明建议使用前增量运算符,因为没有输入参数。但是,返回值应该是一个引用。正确的实现应该是:

代码语言:javascript
复制
Seti& Seti::operator++()
{
    if (this->freq < 9)
        this->freq += 1;
    return *this;
}

另一方面,如果您想实现post-increment运算符,正确的实现应该是:

代码语言:javascript
复制
Seti Seti::operator++(int)
{
    Seti temp(*this);
    if (this->freq < 9)
        this->freq += 1;
    return temp;
}

使用运算符时:

代码语言:javascript
复制
Seti s;
++s; // calls operator++()
s++; // calls operator++(int)

C++标准的13.5.7节显示了这些运算符的官方声明:

代码语言:javascript
复制
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++
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15845872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档