jvi*_*tti 3 c++ operator-overloading
我有一个有string text私人成员的Task类.我访问变量槽const string getText() const;.
我想重载==运算符以检查对象的不同实例是否具有相同的文本.
我bool operator==( const Task text2 ) const;在类标题上声明了一个public 并将其编码为:
bool Task::operator==( const Task text2 ) const {
return strcmp( text.c_str(), text2.getText().c_str() ) == 0;
}
Run Code Online (Sandbox Code Playgroud)
但即使字符串相等,它总是返回false.
所以我在其中添加了一个cout调用bool operator==( const Task text2 ) const;来检查它是否被调用,但什么都没有.
似乎我的自定义==运算符永远不会被调用.
我的标题:
#ifndef TASK_H
#define TASK_H
#include <iostream>
using namespace std;
class Task {
public:
enum Status { COMPLETED, PENDIENT };
Task(string text);
~Task();
// SETTERS
void setText(string text);
void setStatus(Status status);
// GETTERS
const string getText() const;
const bool getStatus() const;
const int getID() const;
const int getCount() const;
// UTILS
//serialize
const void printFormatted() const;
// OVERLOAD
// = expression comparing text
bool operator==( const Task &text2 ) const;
private:
void setID();
static int count;
int id;
string text;
Status status;
};
#endif
Run Code Online (Sandbox Code Playgroud)
编辑了重载操作以使用引用,并远离strcmp:
bool Task::operator==( const Task &text2 ) const {
return this->text == text2.getText();
}
Run Code Online (Sandbox Code Playgroud)
主文件:
using namespace std;
int main() {
Task *t = new Task("Second task");
Task *t2 = new Task("Second task");
cout << "Total: " << t->getCount() << endl;
t->printFormatted();
t2->printFormatted();
if( t == t2 ) {
cout << "EQUAL" << endl;
}
else {
cout << "DIFF" << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*eas 11
Task *t = new Task("Second task");
Task *t2 = new Task("Second task");
// ...
if( t == t2 ) {
Run Code Online (Sandbox Code Playgroud)
您不是在比较Task对象,而是指向Task对象的指针.指针比较是语言的原生,并且比较对象的标识(即true仅当两个指针引用同一个对象或两者都为空时才会产生).
如果要比较需要取消引用指针的对象:
if( *t == *t2 ) {
Run Code Online (Sandbox Code Playgroud)
你写了:
作为 C/C++ 的初学者,我有时会对指针和引用感到困惑。
该问题的解决方案很简单:不要使用指针。与 C 不同,C++ 允许您编写完全有用的程序,而无需直接使用指针。
以下是您编写程序的方式:
int main() {
Task t("Second task");
Task t2("Second task");
std::cout << "Total: " << t.getCount() << "\n";
t.printFormatted();
t2.printFormatted();
if( t == t2 ) {
std::cout << "EQUAL\n";
}
else {
std::cout << "DIFF\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
别打电话new。你确实不需要它。正如当前接受的答案指出的那样,指针的使用是问题的根本原因。
不要使用using namespace std;. 它引入了微妙的错误(您的程序中没有,但最好避免它。)
std::endl如果您的意思是,请不要使用'\n'。'\n'意思是“结束这一行”。std::endl意思是“结束这一行并刷新输出”。