朋友/过载'<'有自己的班级

时间:2012-06-13 11:48:18

标签: c++ operator-overloading

  

可能重复:
  Friending '>>' with own class

我想和朋友'<'运算符与我自己的类,但它没有注意到我的语法错误,但我得到了很快的编译错误:

错误:

**** Internal Builder is used for build               ****
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o ..\main.cpp
In file included from c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/algorithm:63:0,
                 from ..\main.cpp:8:
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/bits/stl_algo.h: In function '_RandomAccessIterator std::__unguarded_partition(_RandomAccessIterator, _RandomAccessIterator, const _Tp&) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<RAngle*, std::vector<RAngle> >, _Tp = RAngle]':
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/bits/stl_algo.h:2253:70:   instantiated from '_RandomAccessIterator std::__unguarded_partition_pivot(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<RAngle*, std::vector<RAngle> >]'
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/bits/stl_algo.h:2284:54:   instantiated from 'void std::__introsort_loop(_RandomAccessIterator, _RandomAccessIterator, _Size) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<RAngle*, std::vector<RAngle> >, _Size = int]'
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/bits/stl_algo.h:5330:4:   instantiated from 'void std::sort(_RAIter, _RAIter) [with _RAIter = __gnu_cxx::__normal_iterator<RAngle*, std::vector<RAngle> >]'
..\main.cpp:13:24:   instantiated from here
c:\mingw\bin\../lib/gcc/mingw32/4.6.1/include/c++/bits/stl_algo.h:2215:4: error: passing 'const RAngle' as 'this' argument of 'bool RAngle::operator<(RAngle)' discards qualifiers [-fpermissive]

类和重载函数:

class RAngle
{
public:
    int x,y,l; 
    int solution,prec;
    RAngle(){
    }

    RAngle(int i,int j,int k){
        x=i,y=j,l=k;
    }

    bool operator<(const RAngle rhs)
    {
        if(l < rhs.l){
            return true;
        }
    return 0;
    }
};

出现错误(main.cpp):

void descrSort(vector <RAngle> &l){
    sort(l.begin(),l.end());
    reverse(l.begin(),l.end());

    for(unsigned i=0; i<l.size();i++){
        cout<<l[i]<<endl;
    }

}

1 个答案:

答案 0 :(得分:3)

这是否已经添加到您关于此主题的上一个问题?

bool operator<(const RAngle rhs)

应该是

bool operator<(const RAngle& rhs) const

应该修复错误。将不修改状态的方法标记为const是一个好习惯。