Doubt with operator ==

1

Having the following operator declared in a string class, would it be correct to use it in a split class in the following way?

Operator:

  bool CCadena::operator==(const CCadena& obj) const {
  return strcmp(m_pText, obj.m_pText) == 0;
}

function:

if(m_nomLocal==nomEquip)
    {
        return true;
    }
    else if(m_nomVisitant==nomEquip)
    {
        return true;
    }
    else
    {
        return false;
    }

I need to compare if the content of the nomlocal and visitor varianles are equal to the parameter nomEquip and return true of being so and false otherwise.

    
asked by ElPatrón 16.03.2017 в 18:14
source

2 answers

1

If you are interested in knowing if nomEquip is equivalent to m_nomLocal or m_nomVisitant and assuming that the three variables are of type CCadena , it would be more natural to leave it like this:

if(m_nomLocal==nomEquip || m_nomVisitant==nomEquip)
{
  return true;
}
else
{
  return false;
}

or like this:

return (m_nomLocal==nomEquip || m_nomVisitant==nomEquip);

The two options are equivalent, of course your method would also work, but it is more repetitive and, therefore, prone to errors.

    
answered by 17.03.2017 / 00:10
source
0

It seems to me that m_nomLocal , m_nomVisitant and nomEquip are variables const char * while operator == that defined is used to compare objects CCadena . Your operator == compares members m_pText of CCadena s and therefore does not serve to compare m_local, m_nomVisitant and nomEquip directly.

#include <iostream>
#include <string.h>

class CCadena{
public:
    const char* m_pText;
    CCadena(const char* pText): m_pText(pText){}
    bool operator==(const CCadena& obj) const {
        return strcmp(m_pText, obj.m_pText) == 0;
    }
};

int main(){
    CCadena local("aaaa");
    CCadena equip("bbbb");
    std::cout << (local == equip) << std::endl;

    CCadena visitante("aaaa");
    std::cout << (local == visitante) << std::endl;
}
    
answered by 16.03.2017 в 19:47