集合的重载运算符

时间:2016-10-22 18:11:37

标签: c++ overloading

我只是建立了一个迷你程序,以了解它是如何工作的,因为我需要这个更困难的东西,但我不能做到这一点。

我认为我需要定义运算符重载但我不知道如何因为它们是set<set<a>>的两个对象

如果你编译,你会发现一个很大的错误,它注意到他无法比较myset == myset2,我认为它会对运营商!==

#include <set>
using namespace std;

class a{
private:
     int a_;
public:
    int get_a() const{ return a_; }
     void set_a(int aux){ a_=aux;}
     bool operator < (const a& t) const{
         return this->get_a() < t.get_a();
     }
};


class b{
private:
     set<set<a> > b_;
public:
     void set_(set<a> aux){ b_.insert(aux); }
     //Overload operators?
};


int main(){
    b myset;    
    b myset2;

    set<a> subset1;
    set<a> subset2;

    a myint;

    myint.set_a(1);
    subset1.insert(myint);

    myint.set_a(2);
    subset1.insert(myint);

    myint.set_a(3);
    subset1.insert(myint);

    myint.set_a(5);
    subset2.insert(myint);

    myint.set_a(6);
    subset2.insert(myint);

    myint.set_a(7);
    subset2.insert(myint);

    myset.set_(subset1);
    myset.set_(subset2);

    myset2.set_(subset1);
    myset2.set_(subset2);


    if(myset == myset2){
        cout << "They are equal" << endl;
    }

    if(myset != myset2){
        cout << "They are different" << endl;
    }

    b myset3;

    myset3 = myset2; //Copy one into other

}

2 个答案:

答案 0 :(得分:1)

为了使代码正常工作,您需要指定以下运算符(注意:默认情况下不会创建它们)

class a{
private: 
     int a_;
public: 
    int get_a() const{ return a_; }
    void set_a(int aux){ a_=aux;}

    /* needed for set insertion */
    bool operator < (const a& other) const {
        return this->get_a() < other.get_a();
    }

    /* needed for set comparison */
    bool operator == (const a& other) const {
        return this->get_a() == other.get_a();
    }
};



class b{
private:
     set<set<a> > b_;
public:
     void set_(set<a> aux){ b_.insert(aux); }

     /* needed, because myset == myset2 is called later in the code */
     bool operator == (const b& other) const {
        return this->b_ == other.b_;
     }

     /* needed, because myset != myset2 is called later in the code */
     bool operator != (const b& other) const {
        return !(*this == other);
     }
};

您还应该查看http://en.cppreference.com/w/cpp/container/set并查看其他操作符std::set在其元素内部使用的内容。

答案 1 :(得分:0)

默认情况下,编译器不会生成任何运算符(默认值operator=(const T&)operator=(T&&)除外)。您应该明确定义它们:

class b{
private:
     set<set<a> > b_; 
public:
     void set_(set<a> aux){ b_.insert(aux); }
     //Overload operators?

     bool operator==(const b& other) const {
         return b_ == other.b_;
     }

     bool operator!=(const b& other) const {
         return b_ != other.b_;
     } 
};

然而,这只是没有解决的情况。虽然已经为std::set<T>定义了比较运算符,但只有T的运算符才有效。因此,在这种情况下,您必须为operator==课程定义operator!=a,方法与我在b课程中展示的方式相同。