努力让'=='运算符重载工作(C ++)

时间:2010-08-19 22:09:33

标签: c++ operator-overloading equality

好吧,不知道我在这里做什么,除了它不对。试图重载一个类的'=='方法,它只是......不工作。至少,我从我的main得到了错误的回复,并且'=='的实现中的cout没有输出。

这是我的三个文件:

// 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;
}

所以问题是 - 我做错了什么?我在某处可能是一个非常愚蠢的错误道歉,但我无法发现它。

2 个答案:

答案 0 :(得分:11)

tc == tc1比较指针值。它“应该”为*tc == *tc1,但我不明白为什么你会在第一时间动态分配。

自动(堆栈)分配是首选,只有在您需要对象独立于范围时才动态分配。 (然后使用自动分配的智能指针跟踪它,这将在适当的时候删除指针。)


此外,运营商应为const,因为它不会修改this

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

但更好的是免费功能:

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

哪个可能是朋友。 (自由函数总是首选,加上这允许5 == tc工作。)

答案 1 :(得分:4)

您正在比较指针。试试这个:

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

两个评论:

  • 你应该释放分配的内存 删除或使用智能指针
  • 您应该声明operator == const

    bool operator==(const TestClass& other) const

相关问题