什么时候可以比较指向同一个对象在c ++中的指针? [英] When can I compare pointers to the same object in c++?

查看:125
本文介绍了什么时候可以比较指向同一个对象在c ++中的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一些类层次结构(可能,有各种继承 - public,private,public virtual,multi-inheritance等):

For example, I have some class hierarchy (possibly, with all kinds of inheritance - public, private, public virtual, multi-inheritance, etc.):

class A {
  int a;
public:
  virtual ~A() {}
};

class B: public A { int b; };
class C: public virtual B { int c; };
class E: public virtual B { int e; };
class F: public C, public E { int f; };

使用casts获取指向主big对象的每个子对象的指针:

Using casts I get pointers to every sub-object of the main "big" object:

F * f = new F;
E * e = f;
C * c = f;
B * b = f;
A * a = f;

我可以比较这些指针对的相等性(operator ==),为什么?
比较是否使用delta逻辑或其他技术?

What pairs of these pointers may I compare for equality (operator==) and why? Will the comparison use delta-logic or some other technique?

当我不能比较指向同一个复杂对象的指针时,有什么可能的情况?
它可以是什么类型的对象?

What are the possible situations, when I can't compare pointers to the same complex object? What kind of object it can be?

我希望所有指向同一对象的指针总是相等的。

I expect, that all of the pointers to the same object are always equal.

推荐答案

如果一个指针类型可以隐式转换为另一个指针,则可以比较两个指针;也就是说,如果它们都指向同一类型,或者一个指向另一个的基类。转换将对地址进行必要的调整,以便如果两个指针指向同一个对象,它们将比较相等。

You can compare two pointers if one pointer type is implicitly convertible to the other; that is, if they both point to the same type, or one points to a base class of the other's. The conversion will make the necessary adjustment to the address so that, if both pointers point to the same object, they will compare equal.

在这种情况下,对 c == e ,因为 C E 是从另一个派生的。要比较这些,你需要交叉转换,或将两者转换为它们的共同基类;

In this case, you can compare any pair except c == e, since neither of C nor E is derived from the other. To compare those, you would either need to cross-cast, or to convert both to their common base class; neither of these can be done implicitly.

顺便说一下,您的代码中不需要 dynamic_cast ,因为你正在转换为基类指针,并且可以隐式完成安全转换。

By the way, there's no need for dynamic_cast in your code, since you're casting to base class pointers and that safe conversion can be done implicitly.

这篇关于什么时候可以比较指向同一个对象在c ++中的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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