为什么C ++编译器不定义operator ==和operator!=? [英] Why don't C++ compilers define operator== and operator!=?

查看:122
本文介绍了为什么C ++编译器不定义operator ==和operator!=?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个很大的粉丝,让编译器做尽可能多的工作,为你尽可能。当编写一个简单类时,编译器可以为'free'提供以下内容:

I am a big fan of letting the compiler do as much work for you as possible. When writing a simple class the compiler can give you the following for 'free':


  • 默认(空)构造函数

  • 一个复制构造函数

  • 一个析构函数

  • 赋值运算符( operator =

  • A default (empty) constructor
  • A copy constructor
  • A destructor
  • An assignment operator (operator=)

但它似乎不能给你任何比较运算符,例如 operator == operator!= 。例如:

But it cannot seem to give you any comparison operators - such as operator== or operator!=. For example:

class foo
{
public:
    std::string str_;
    int n_;
};

foo f1;        // Works
foo f2(f1);    // Works
foo f3;
f3 = f2;       // Works

if (f3 == f2)  // Fails
{ }

if (f3 != f2)  // Fails
{ }

这是否有很好的理由?为什么要执行逐个成员比较是一个问题?显然,如果类分配内存,那么你需要小心,但对于一个简单的类肯定是​​编译器可以为你做这个?

Is there a good reason for this? Why would performing a member-by-member comparison be a problem? Obviously if the class allocates memory then you'd want to be careful, but for a simple class surely the compiler could do this for you?

推荐答案

编译器不知道你是想要一个指针比较还是一个深层(内部)比较。

The compiler wouldn't know whether you wanted a pointer comparison or a deep (internal) comparison.

只是没有实现它,让程序员做自己。然后他们可以做出他们喜欢的所有假设。

It's safer to just not implement it and let the programmer do that themselves. Then they can make all the assumptions they like.

这篇关于为什么C ++编译器不定义operator ==和operator!=?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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