首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >增量后超载中的冗余?

增量后超载中的冗余?
EN

Stack Overflow用户
提问于 2014-03-05 01:32:05
回答 2查看 117关注 0票数 0
代码语言:javascript
复制
// The following operator++() represents overloading of pre-increment 
MyIncrDecrClass& operator++()  
{ 
    ++this->m_nCounter; 
    return *this; 
} 

// Passing dummy int argument is to mention overloading of post-increment  
MyIncrDecrClass& operator++(int)  
{ 
    this->m_nCounter++; 
    return *this; 
} 

这就是post和预增量操作符的实现方式,但在我的例子中,我不能这样实现它,所以我就是这样做的:

代码语言:javascript
复制
VLongInt& VLongInt::operator++()
{
    ... //BUILD TEMP vector
    this->vec = temp;
    return *this;
}

VLongInt& VLongInt::operator++(int)
{
    this->vec = this.vec; //seems unnecessary
    ... //BUILD TEMP vector
    this->vec = temp
    return *this;
}

有什么不对劲吗?两者似乎应该以同样的方式执行。只有头文件应该不同,对吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-05 01:42:38

您的后增量运算符重载示例是错误的。

欧洲工商管理学院

代码语言:javascript
复制
// Passing dummy int argument is to mention overloading of post-increment  
MyIncrDecrClass& operator++(int)  
{ 
    this->m_nCounter++; 
    return *this; 
} 

应该有

代码语言:javascript
复制
// Passing dummy int argument is to mention overloading of post-increment  
MyIncrDecrClass operator ++( int )  
{
    MyIncrDecrClass tmp( *this );

    ++this->m_nCounter; 

    return tmp; 
}

ALso你的问题完全不清楚。实际上,您定义了同一个操作符两次

代码语言:javascript
复制
VLongInt& VLongInt::operator++()
{
    //...
    return *this;
}

VLongInt& VLongInt::operator++()
{
    //...
    return *this;
}

我看不出有什么不同。此外,您没有显示您的类定义,因此,您的问题不能说什么。它是未知的。

至少就像您自己说的那样,您的后增量操作符应该使用一个类型为int的虚拟参数声明。它必须返回一个临时对象。

代码语言:javascript
复制
VLongInt  VLongInt::operator ++( int )

代码语言:javascript
复制
const VLongInt  VLongInt::operator ++( int )
票数 2
EN

Stack Overflow用户

发布于 2014-03-05 01:40:05

有什么不对劲吗?

是的,您的代码违反了ODR (一个定义规则)。第3.2/1节将其定义为:

任何转换单元都不得包含任何变量、函数、类类型、枚举类型或模板的多个定义。

您应该定义这两个函数:

代码语言:javascript
复制
VLongInt& VLongInt::operator++();
const VLongInt VLongInt::operator++(int);

具体来说,请注意post增量运算符应该返回const TT ( T是类类型)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22186751

复制
相关文章

相似问题

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