[英]Check if two classes are equal (identity)
I have looked at multiple SO questions and forum posts regarding this, but all posts have either related to pointers (not class instances) or checking equivalence (not identity). 我已经看过关于此的多个SO问题和论坛帖子,但是所有帖子都与指针(不是类实例)或检查对等关系(不是身份)有关。 Right now I'm using the ==
operator on this
and the variable containing the other class object. 现在,我使用==
操作员this
和包含其他类对象的变量。 It works, but Eclipse is spitting out a warning no match for operator==(operand types are Class* and Class
Here are the relevant files: 它可以工作,但是Eclipse会发出警告no match for operator==(operand types are Class* and Class
以下是相关文件:
#include <iostream>
#include "Class.h"
using namespace std;
int main() {
Class a;
Class b;
cout << "Are a & b the same instance? " << a.sameInstance(b) << endl;
return 0;
}
#pragma once
class Class {
public:
Class();
bool sameInstance(Class);
};
#include "Class.h"
Class::Class() {
}
bool Class::sameInstance(Class c) {
return this == c;
}
Edit: I converted to Class pointers: 编辑:我转换为类指针:
#pragma once
class Class {
public:
Class();
bool sameInstance(Class*);
};
#include "Class.h"
Class::Class() {
}
bool Class::sameInstance(Class* c) {
return this == c;
}
But I'm not sure how to pass b as a pointer in Main.cpp. 但是我不确定如何在Main.cpp中将b作为指针传递。 Left unchanged, it's giving me the error Invalid arguments Candidates are bool sameInstance(Class*)
保持不变,这会给我错误Invalid arguments Candidates are bool sameInstance(Class*)
Edit2: I put an & before a variable name to convert it to a pointer. Edit2:我在变量名前加上&,以将其转换为指针。 So instead of a.sameInstance(b)
, it'd be a.sameInstance(&b)
. 因此,它不是a.sameInstance(b)
,而是a.sameInstance(&b)
。
In your sameInstance
method, you must pass the parameter either by reference or by pointer. 在sameInstance
方法中,必须通过引用或指针传递参数。 Passing by value will not work, because the function will be operating on a copy of the object, which is obviously a different instance. 按值传递将不起作用,因为该函数将对对象的副本进行操作,这显然是不同的实例。
By reference: 引用:
bool Class::sameInstance(const Class& c) {
// Take address of c to get a pointer which can be compared to this
return this == &c;
}
// main()
cout << "Are a & b the same instance? " << a.sameInstance(b) << endl;
By pointer: 通过指针:
bool Class::sameInstance(const Class* p) {
// p is already a pointer which can be compared to this
return this == p;
}
// main()
// Take the address of b to pass to sameInstance()
cout << "Are a & b the same instance? " << a.sameInstance(&b) << endl;
Passing by reference is better idiomatic C++. 通过引用传递是更好的惯用C ++。
In both cases, you should use const
, because sameInstance()
doesn't modify its parameter. 在这两种情况下,都应使用const
,因为sameInstance()
不会修改其参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.