【问题标题】:c++ set<> of class objects. Using own comparer giving error: C2804: binary 'operator <' has too many parametersc++ set<> 类对象。使用自己的比较器给出错误:C2804:二进制“运算符 <”参数过多
【发布时间】:2012-03-20 08:31:51
【问题描述】:

我写了一段c++代码如下:

#include<iostream>
#include<string>
#include<set>
using namespace std;

class data{
    int i;
    float f;
    char c;
public:
    data();
    data(int i,float f,char c);
};

data::data(int i,float f,char c){
    this->i=i;
    this->f=f;
    this->c=c;
};

class LessComparer{
    bool operator<( const data& a1, const data& a2 ) const{
        return( a1.i < a2.i ||
            (!(a1.i > a2.i) && (a1.f < a2.f)) ||
            (!(a1.i > a2.i) && !(a1.f > a2.f) && (a1.c < a2.c)));
    }
};

int main(){
    set<data,LessComparer> s;
    set<data,LessComparer>::iterator it;
    s.insert(data(1,1.3,'a'));
    s.insert(data(2,2.3,'b'));
    s.insert(data(3,3.3,'c'));
    if((it=s.find(data(1,1.3,'a'))!=s.end())
        cout<<(*it).i;
    cin.get();
    return 0;
}

在编译时它给出的第一个错误是:

error: C2804: binary 'operator <' has too many parameters

以及 LessComparer 类中的许多其他错误。

我不熟悉这种重载。请帮助我更正代码。

谢谢。

【问题讨论】:

    标签: c++ operator-overloading set


    【解决方案1】:

    LessComparer 需要实现 operator() 而不是 operator

    bool operator()( const data& a1, const data& a2 ) const
    

    【讨论】:

      【解决方案2】:

      如果您在类中声明&lt; 运算符,则第一个参数将隐含为this

      要使用 2 个参数声明它,您必须在类的上下文之外这样做。

      下面将LessComparer 类型的对象与data 类型的对象进行比较。

      class LessComparer{
          bool operator < ( const data& a2 ) const{
              //...
          }
      };
      

      如果要比较两个data 对象,请在class data 内部或类外部声明运算符,并带有两个参数:

      class data{
      public:
          bool operator < ( const data& a2 ) const{
             //...
          }
      };
      

      异或

      class data
      {
         //...
      };
      bool operator<( const data& a1, const data& a2 ){
         //...
      }
      

      【讨论】:

      • @NDThokare 没有。这是一个完全不同的问题。问一个新问题。
      • question已发布
      • @NDThokare 如果您阅读了我的回答,您将不需要新问题。
      猜你喜欢
      • 2016-06-26
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      相关资源
      最近更新 更多