为什么运算符重载==不起作用?

时间:2020-10-09 14:12:10

标签: c++ overloading operator-keyword

我需要使用重载==来检查这两个向量是否相等,但它始终仅在else语句中起作用。

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
class Set {
public:
    vector<int> mult;
    friend bool operator ==(const Set&, const Set&);
};
bool operator ==(const Set& a, const Set& b) {
    return (a.mult == b.mult);
}


int main()
{
    Set* set_1 = new Set;
    Set* set_2 = new Set;
    for (int i = 1; i <= 5; i++)
       set_1->mult.push_back(i);
    for (int i = 1; i <= 5; i++)
        set_2->mult.push_back(i);

    if (set_2 == set_1) {
        cout << "True ";
    }
    else {
        cout << "False";
    }
}

2 个答案:

答案 0 :(得分:1)

set_1set_2都不是集合。它们是集合的指针。您正在比较指针而不是集合,因此将不会调用您的比较运算符(接受集合引用操作数)。

当您将一个指针与另一个指针进行比较时,您正在比较它们是否指向同一对象。 set_1set_2指向不同的对象,因此比较不相等。

因此,您的问题不是您的运算符重载不起作用,而是您没有首先使用该运算符重载。要解决该问题,您需要比较指针集而不是指针。为了获得对指针集的引用,您可以使用间接操作符通过指针进行间接操作。

甚至更好的是,您可以首先使用set变量。似乎没有理由使用动态分配集。


P.S。避免拥有裸露的指针。您的程序泄漏内存。

答案 1 :(得分:0)

对Set使用继承,而不是在类中使用向量成员。如果为您动态分配了集合,请随后进行清理。

#include <iostream>
#include <vector>

class Set : public std::vector<int>
{};

int main()
{
    Set * pa = new Set; //If dynamic allocation is mandatory
    pa->push_back(3);

    Set * pb = new Set;
    pb->push_back(3);

    if (*pa == *pb) //Uses the inherited == operator from std::vector<int>
    {
        std::cout << "a=b" << std::endl;
    }
    else
    {
        std::cout << "a<>b" << std::endl;
    }

    delete pa; //Clean up!
    delete pb;
}