【问题标题】:friend/overload '<' with own class [duplicate]朋友/重载'<'用自己的类[重复]
【发布时间】:2012-06-13 11:48:17
【问题描述】:

可能重复:
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;
    }

}

【问题讨论】:

  • 你已经问过了。如果您阅读了我对上一个问题的回答,您就会明白将 operator&lt; 设为 const 方法是经验法则
  • -1: 重复提问,题目错误。问题中没有friend

标签: c++ operator-overloading


【解决方案1】:

这不是已添加到您关于此主题的最后一个问题中吗?

bool operator<(const RAngle rhs)

应该是

bool operator<(const RAngle& rhs) const

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

【讨论】:

  • 为了更详细的解释:内部std::sort 不同位置的值进行比较。选择一个元素作为枢轴,并调用一个将范围划分为小于/大于该值的元素的函数。该函数通过常量引用获取用于分区的值,并尝试调用您的operator&lt;。当常量引用用作表达式的左侧时,您的 operator&lt; 不能使用,因为该函数不是 const,并且调用非常量函数(从编译器的角度来看)可能会改变const 参考。
  • 糟糕,没有发现丢失的参考印记。塔。
  • 不是真的有人告诉我让它从 int 函数变为 bool,但谢谢你的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多