-2

I have a class MyClass within a namespace MyNameSpace, and I define a == operator in test unit, so, classes could be copmared.

The unit test doesn' compile 'cause theres no operator == match for const MyNameSpace Myclass, MyNamespace MyClass, even if I have it in unit test.

Without using a namespace works as expected.

Lets say we have:

namespace MyNamespace {
class MyClass {
public :
    QString a;
};
}

and in test unit:

....
#include "myclass.h"
using namespace MyNamespace;
....

test_case1 {
    MyClass myClass;
    myClass.a = "test";

    MyClass myClass2;
    myClass2.a = "test";

    QCOMPARE(myClass, myClass2); //Fails to compile 
}

operator==(const MyNamespace::MyClass &class1, const MyNamespace::MyClass &class2) {
    return (class1.a == class2.a);
}

1 Answers1

0

I solved by wrapping the definition of operator == into std namespace

namespace std {
    bool operator==(const MyNamespace::MyClass class1, const MyNamespace::MyClass class2)
    {
        return (class1.a == class2.a);       
    }
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • 1
    Adding function definitions to std is [undefined behavior](https://en.cppreference.com/w/cpp/language/extending_std). This is a terrible idea. – Alex Huszagh Aug 31 '19 at 17:24
  • 1
    Why not just add a friend function to one of the classes? – Alex Huszagh Aug 31 '19 at 17:27
  • 1
    You seem pretty new to C++, so I will just throw this out: invoking undefined behavior as a programmer is the source of many errors and should be avoided whenever possible. Here's a great blog on the subject: http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html – Alex Huszagh Aug 31 '19 at 17:51