Domanda

i have a class which needs to implement the operator== and return type of it is bool. I'm not sure is below code the correct way to implement it.

//MyTest.hpp file

class Test {
public:

    Test();
    virtual ~Test();

    int x,y;

    bool operator==(const Test &v);

};

// MyTest.cpp file

bool Test::operator==(const Test &v) {
    return (x== v.x) && (y==v.y);
}

even though the code compiles is this standard way to implement we need to use template. Should i use template way of implementation like below code :

template <class T>
bool operator==(const T &v);
È stato utile?

Soluzione 2

As others have mentioned, using a template without any reason to do so is neither standard nor recommended. However assuming you want operator== to be more like one of the default comparison operators you should either mark it const (otherwise you cannot compare two const Test) like so

class Test {
public:
    Test();
    virtual ~Test();

    int x,y;

    bool operator==(const Test &v) const;
};

// MyTest.cpp file

bool Test::operator==(const Test &v) const {
    return (x== v.x) && (y==v.y);
}

, or make it a free function (in the same namespace for ADL) taking two const Test & (preferred) like so

class Test {
public:
    Test();
    virtual ~Test();

    int x,y;
};

bool operator==(const Test &a, const Test &b);

// MyTest.cpp file

bool operator==(const Test &a, const Test &b) {
    return (a.x==b.x) && (a.y==b.y);
}

If any access to private members is required the free function can always be marked friend. In simple cases such as the one in this example it can be advantageous to furthermore define it in the header and marking it inline.

Altri suggerimenti

Don't use templates unless you need to. Does it make sense for Test to be comparable with any type? I doubt so.

Also there's no "Standard way" because the standard does not impose a strict way to implement operator== (I think it mentions something on the return type, but I doubt it actually enforces anything).

It's a good idea to make it return a bool and make it does what people expect it does (compare the two objects in a meaningful way).

And finally, you should mark your current one const:

bool operator==(const Test &v) const;

Unless it actually modifies the invoking object, which is definitely something you don't want it to do.

Please do not use templates matching anything:

template <class T>
bool operator==(const T &, const T &);

That one will put you in all kinds of trouble !

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top