复制分配运算符=自我分配检查错误 [英] copy assignment operator= self-assignment check error

查看:58
本文介绍了复制分配运算符=自我分配检查错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个用声明的类

If I have a class declared with

class Person
{
  public:
    Person(const int age);  // constructor
    Person(const Person & other);
    Person & operator=(const Person & other);  // copy assignment operator=
    ~Person();
};

并定义这样的自我分配检查

and define self-assignment check like this

Person & Person::operator=(const Person & other)  // copy assign operator=
{
  if (*this != other)
  {... copy data ...}
  return *this;
}

然后g ++发出错误消息:

then g++ issues an error:

错误:与'operator!='不匹配(操作数类型为'Person''const Person ')

error: no match for ‘operator!=’ (operand types are ‘Person’ and ‘const Person’)

但是如果我将其更改为

Person & operator=(Person& other);

然后g ++发出错误消息:

then g++ issues an error:

错误:与'operator!='不匹配(操作数类型为'Person''Person')

error: no match for ‘operator!=’ (operand types are ‘Person’ and ‘Person’)

在第二种情况下,如果类型相同,为什么不匹配?

Why, in the second case, no match if types are the same?

还有一个后续问题:

为什么只有此检查才被视为有效?

Why only this check is considered valid ?

if (this != &other)

推荐答案

类型相同并不重要.是否定义运算符很重要.编译器没有为您提供默认的 operator!= ,显然您还没有自己定义它.

It doesn't matter that the types are the same. It matters whether or not the operator is not defined. The compiler does not provide a default operator!= for you, and apparently you haven't defined it yourself.

在这种情况下,

if (this != &other)

这是有效的,因为它是指针比较.指针比较是一项内置功能,可用于任何指针类型.

This is valid because it is a pointer comparison. Pointer comparison is a built-in feature that is available to any pointer type.

这篇关于复制分配运算符=自我分配检查错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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