比较自我分配的指针 [英] Comparing pointers for self-assignment

查看:142
本文介绍了比较自我分配的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图重载一个简单的C ++类名为Set的包含动态数组的int运算符。对于=运算符,我首先要检查自我分配,所以我想比较2个指针,看看它们是否有相同的内存地址。这里是代码:

I am trying to overload the = operator on a simple C++ class called Set that contains a dynamic array of ints. 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. Here's the code:

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

错误出错是表达式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.

推荐答案

要检测自我指派,您需要

To detect self-assignment you need

if(&setEqual == this)

你不应该使用

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.

这篇关于比较自我分配的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆