开发者

Struggling to get '==' operator overloading to work (C++)

Okay, not sure what I'm doing here, other than it's not right. Trying to overload the '==' method of a class, and it's just... not working. At least, I get a false back from my main, and the cout in the implementation of '==' doesnt output.

These are my three files:

// TestClass.h

#ifndef TESTCLASS_H
#define TESTCLASS_H

class TestClass {
public:
    TestClass(int contents);
    TestClass(const TestClass& orig);
    virtual ~TestClass();
    bool operator==(const TestClass& other);
private:
    int contents;
};

#endif  /* TESTCLASS_H */



// TestClass.cpp

#include <iostream>

#include "TestClass.h"

TestClass::TestClass(int contents) {
    this->contents = contents;
}

TestClass::TestClass(const TestClass& orig) {
    this->contents = orig.contents;
}

TestClass::~TestClass() {
}

bool TestClass::operator ==(const TestClass& other) {
    std::cout << "COMPARING" << std::endl;
    return (contents == other.contents);
}


// Main.cpp

#include <cstdlib>
#include <iostream>

#include "TestClass.h"

using namespace std;

/*
 * 
 */
int main(int argc, char** argv) {

    TestClass* tc = new TestClass(1);
    TestClass* tc1 = new TestClass(1);

    cout << (tc == tc1) << endl;

    return 0;
}

So the question is - what have I done wrong? I apologise for what is probably a very silly m开发者_Python百科istake somewhere, but I just can't spot it.


tc == tc1 compares pointer values. It "should" be *tc == *tc1, but I don't get why you'd dynamically allocate in the first place.

Automatic (stack) allocation is highly preferred, only dynamically allocate when you need the object to be independent of scope. (And then keep track of it with automatically allocated smart pointers, which will delete the pointer when it's appropriate.)


Also, the operator should be const, because it doesn't modify this:

//                                      vvvvv
bool operator==(const TestClass& other) const;

Even better, though, is a free function:

bool operator==(const TestClass& lhs, const TestClass& rhs);

Which would possibly be a friend. (Free-functions are always preferred, plus this allows 5 == tc to work.)


You are comparing pointers. Try that instead:

cout << (*tc == *tc1) << endl;

Two remarks:

  • You should free allocated memory with delete, or use a smart pointer
  • You should declare operator== const:

    bool operator==(const TestClass& other) const

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜