The fight for overloading the operator "==" to work (C ++)

Well, I'm not sure what I'm doing here, but this is not the case. Trying to overload the class's "==" method, and it just ... doesn't work. At least I get false feedback from mine main, but coutin the implementation '==' does not 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 did I do wrong? I apologize for what is probably a very stupid mistake, but I just can’t notice it.

+3
source share
2 answers

tc == tc1compares pointer values. It should be *tc == *tc1, but I don’t understand why you dynamically allocate in the first place.

() , , , . ( , , .)


, const, this:

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

, , :

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

. ( , 5 == tc.)

+11

. :

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

:

  • operator == const:

    bool operator==(const TestClass& other) const

+4

Source: https://habr.com/ru/post/1760643/


All Articles