首页 > 解决方案 > 比较类和对象的向量时如何定义 == 运算符?

问题描述

我希望我的程序在向量具有相同颜色超过 3 次时停止。在这里,我使用了 'if(b==all_colors[i])' 但我得到了错误。这是因为我没有使用模板吗?我必须重写整个代码吗?

#include<iostream>
#include<string>
#include<sstream>
#include<vector>

using namespace std;

class Bag
{
    string marble;

public:
    Bag(string marble)
    {
        this->marble=marble;
    }

    string add_marble()
    {
        return marble;
    }
};

class Marble_exception
{
    vector<Bag>all_colors;
    int count=0;

public:
    void add_color(Bag b)
    {
        for(int i=0; i<all_colors.size(); i++)
        {
            if(b==all_colors[i])
            {
                count++;
            }
        }

        if(count>=3)
        {
            cout<<"Sorry, you already have three of these marbles.\n\n";
        }
        else
        {
            all_colors.push_back(b);
            cout<<"added.\n\n";
        }
    }
};

标签: c++

解决方案


不,您不必重写整个代码。错误是因为operator==您的Bag班级没有。C++ 知道如何比较vector<T>,但前提是它也知道如何比较T。将此添加到您的代码中

class Bag
{
    ...
    // new code
    friend bool operator==(const Bad& x, const Bag& y)
    {
        return x.marble == y.marble;
    };
    // new code
};

这段代码定义了operator==for所以现在使用forBag应该没有问题。==vector<Bag>


推荐阅读