在c ++中运算符重载的后递增

时间:2011-11-04 07:50:16

标签: c++ operator-overloading post-increment

这是我的帖子增量运算符重载声明。

loc loc::operator++(int x)
{
    loc tmp=*this;
    longitude++;
    latitude++;
    retrun tmp;
} 

我的类构造函数

loc(int lg, int lt) 
{
   longitude = lg;
   latitude = lt;
}

在主要功能中,我编码如下

int main()
{
    loc ob1(10,5);
    ob1++;
}

在编译时,我收到以下错误

  

opover.cpp:56:5:错误:'loc loc :: operator ++(int)'的原型   不匹配任何类'loc'     opover.cpp:49:5:错误:候选者是:loc   loc :: operator ++()opover.cpp:在函数'int main()'中:   opover.cpp:69:4:错误:没有'operator ++(int)'声明为postfix'++'

3 个答案:

答案 0 :(得分:4)

修复您的班级声明
class loc
{
    // ...
    loc operator++();
} 

class loc
{
    // ...
    loc operator++(int);
} 

[编辑删除了有关按值返回的错误评论。按值返回当然后缀运算符的通常语义++]

答案 1 :(得分:3)

您应该有++的两个版本:

loc& loc::operator++() //prefix increment (++x)
{
    longitude++;
    latitude++;
    return *this;
} 

loc loc::operator++(int) //postfix increment (x++)
{
    loc tmp(longtitude, langtitude);
    operator++();
    return tmp;
}

当然,两个函数都应该在类原型中定义:

loc& operator++();
loc operator++(int);

答案 2 :(得分:1)

您没有在类定义中声明重载运算符。

你的课应该是这样的:

class loc{
public:
    loc(int, int);
    loc operator++(int);
    // whatever else
}

**编辑**

阅读完评论后,我注意到在您的错误消息中显示您已声明loc operator++(),所以只需解决此问题。

相关问题