Ste*_*hen 3 c++ equality operator-overloading
好吧,不知道我在这里做什么,除了它不对.试图重载一个类的'=='方法,它只是......不工作.至少,我得到了一个错误的回复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;
}
Run Code Online (Sandbox Code Playgroud)
所以问题是 - 我做错了什么?我在某处可能是一个非常愚蠢的错误道歉,但我无法发现它.
GMa*_*ckG 11
tc == tc1比较指针值.它"应该" *tc == *tc1,但我不明白为什么你首先动态分配.
自动(堆栈)分配是首选,只有在您需要对象独立于范围时才动态分配.(然后使用自动分配的智能指针跟踪它,这将在适当的时候删除指针.)
此外,操作员应该const,因为它不会修改this:
// vvvvv
bool operator==(const TestClass& other) const;
Run Code Online (Sandbox Code Playgroud)
但更好的是免费功能:
bool operator==(const TestClass& lhs, const TestClass& rhs);
Run Code Online (Sandbox Code Playgroud)
哪个可能是朋友.(自由功能总是首选,加上这可以5 == tc工作.)
| 归档时间: |
|
| 查看次数: |
208 次 |
| 最近记录: |