简体   繁体   English

比较自我分配的指针

[英]Comparing pointers for self-assignment

I am trying to overload the = operator on a simple C++ class called Set that contains a dynamic array of ints. 我试图在名为Set的简单C ++类上重载=运算符,该类包含一个动态整数数组。 For the = operator, I first want to check for self assignment, so I wanted to compare 2 pointers to make see if they have the same memory address. 对于=运算符,我首先要检查自我分配,因此我想比较2个指针以查看它们是否具有相同的内存地址。 Here's the code: 这是代码:

Set& Set::operator=(const Set& setEqual)
{
//first check for self assignment
if(setEqual == this*)
    cout << "this is self assignment";
}

The error spat out is error: expected primary-expression before ')' token 错误吐出是error: expected primary-expression before ')' token

I believe I'm having a misunderstanding of pointers again, so if anyone could point (ha!) me in the right direction, I'd appreciate it. 我相信我又一次对指针产生了误解,因此,如果有人可以将我指向正确的方向,我将不胜感激。

The error is becuase this* is not valid - * is either infix (in multiplication) or prefix (in dereferencing pointers). 错误是因为this*无效- *是前缀(在乘法中)或前缀(在取消引用指针中)。

You probably want &setEqual == this - that is assigning from an object at the same memory address or setEqual==*this - comparing equality using whatever operator== you have defined 您可能希望&setEqual == this从同一内存地址的对象分配或setEqual==*this使用您定义的任何operator==比较相等

If you want to compare the address of the thing pointed too you really want this: 如果您也想比较所指对象的地址,那么您真的想要这样:

Set& Set::operator=(const Set& setEqual)
{
//first check for self assignment
if(&setEqual == this)
    cout << "this is self assignment";
}

Using (setEqual==*this) as sugested by some of the solutions compares if the objects are equal under operator== . 使用某些解决方案所(setEqual==*this)来比较operator==下的对象是否相等。

To detect self-assignment you need 要检测自我分配,您需要

if(&setEqual == this)

you should never use 你永远不要使用

if(setEqual == *this)

for detecting self-assignment as the latter statement will invoke comparison of the objects, which might be overloaded in the way you don't expect and is likely slower as well. 用于检测自我分配,因为后面的语句将调用对象的比较,这可能会以您不期望的方式过载,并且也可能会变慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM