Problem with operator overload

2

Errors occur when I pass the object of class Name_pairs by output operator << and comparator == .

Header:

    class Name_pairs
    {
    public:
        void read_names(); 
        void read_ages();
        void print() const; 
        void sort(); 
        const std::vector<std::string>& get_name() const { return name; } 
        const std::vector<double>& get_age() const { return age; }    
    private:
        std::vector<std::string>name; 
        std::vector<double>age;     
    };
}

Main.cpp:

int main()
{
    Name_pairs objeto;
    objeto.read_names();
    objeto.read_ages();
    objeto.sort();
    objeto.print();

    Name_pairs objetoDois;
    objetoDois.read_names();
    objetoDois.read_ages();
    objetoDois.sort();
    objetoDois.print();

    if(objeto == objetoDois) cout << "iguais!"; // erro no operador == ;
    else cout << "não são iguais!";
    cout << objeto;  // erro no operador << ;

    system("pause");
    return 0;
}

Settings cpp:

    void Name_pairs::read_names()
    {
        cout << "Entre com os nomes desejados, digite 'SemNome' para               finalizar a lista." << endl;
        string NomesVetor; 

        while (cin >> NomesVetor && NomesVetor != "SemNome")
        {
            for (size_t x = 0; x < name.size(); ++x) // confere se há nomes duplicados 
            {
                if (name[x] == NomesVetor) cout << "Nome repetido." << endl;
            }

            name.push_back(NomesVetor);
        }
    }

    void Name_pairs::read_ages()
    {
        for (size_t x = 0; x < name.size(); ++x)
        {
            cout << "Idade de " << name[x] << ": " << endl;
            double IdadesVetor; 
            cin >> IdadesVetor;
            age.push_back(IdadesVetor);
        }
    }

std::ostream& operator<<(std::ostream& os, const Name_pairs& np)
{
    for (size_t x = 0; x < np.get_name().size(); ++x)
        os << '(' << np.get_name()[x] << ', ' << np.get_age()[x] << ')' << endl;

    return os;

}

 bool operator==(const Name_pairs& a, const Name_pairs& b )
{
    if(a.get_name().size() != b.get_name().size() || a.get_age().size() != b.get_age().size())
    return false;

    for (size_t x = 0; x <a.get_name().size(); ++x)
    {
        if (a.get_name()[x] != b.get_name()[x]) return false;
        if (a.get_age()[x] != b.get_age()[x]) return false;
    }
    return true;
}

bool operator!=(const Name_pairs& a, const Name_pairs& b)
{
    return !(a == b);
}

Remembering: The code compiles if it is removed

 if(objeto == objetodois)cout << "iguais!"; // erro no operador ==
        else cout << "não são iguais!";
        cout << objeto;  // erro no operador << 

da main.

    
asked by anonymous 01.07.2016 / 21:45

1 answer

1

Marv,

Your code is not complete, so it's impossible to rate it. I still exemplify below the implementation of both operators in any class.

It is important to remember that for the example to compile the operator

02.07.2016 / 04:25