我正在尝试解决以下问题:
假设我正在编写一个类,它有一个myMethod修改两者的方法*this和传递的参数:
class MyClass {
//some code here
void myMethod(MyClass& other) {
//modify *this and other
}
};
Run Code Online (Sandbox Code Playgroud)
问题是,当调用以下部分时,我希望该方法不执行任何操作:
MyClass x;
x.myMethod(x);
Run Code Online (Sandbox Code Playgroud)
检查相等是不够的,因为我希望能够为两个相同的对象调用它.
例如,以一种更为实际的方式,假设它MyClass是类似的std::set并且myMethod合并两个集合,清空other.可以合并两个相同的集合,但我显然不能清空并同时填充一个集合.
我该如何检查?任何建议将被认真考虑.
你可以只是比较的地址other到this:
class MyClass {
//some code here
void myMethod(MyClass& other) {
if (this != &other) {
//modify *this and other
}
}
};
Run Code Online (Sandbox Code Playgroud)
由于您通过引用传递,如果将相同的对象传递给您调用它的函数,则指针将是相等的.