C++:比较基类和派生类的指针

标签 c++ inheritance pointers dynamic-cast

我想要一些关于在这种情况下比较指针时的最佳实践的信息:

class Base {
};

class Derived
    : public Base {
};

Derived* d = new Derived;
Base* b = dynamic_cast<Base*>(d);

// When comparing the two pointers should I cast them
// to the same type or does it not even matter?
bool theSame = b == d;
// Or, bool theSame = dynamic_cast<Derived*>(b) == d?

最佳答案

如果你想比较任意类层次结构,安全的做法是让它们多态并使用dynamic_cast

class Base {
  virtual ~Base() { }
};

class Derived
    : public Base {
};

Derived* d = new Derived;
Base* b = dynamic_cast<Base*>(d);

// When comparing the two pointers should I cast them
// to the same type or does it not even matter?
bool theSame = dynamic_cast<void*>(b) == dynamic_cast<void*>(d);

考虑到有时您不能使用 static_cast 或从派生类到基类的隐式转换:

struct A { };
struct B : A { };
struct C : A { };
struct D : B, C { };

A * a = ...;
D * d = ...;

/* static casting A to D would fail, because there are multiple A's for one D */
/* dynamic_cast<void*>(a) magically converts your a to the D pointer, no matter
 * what of the two A it points to.
 */

如果 A 是虚拟继承的,您也不能将 static_cast 转换为 D

关于C++:比较基类和派生类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5662719/

相关文章:

c++ - 修改系统卷后如何修改WASAPI回送捕获卷?

c++ - C2059 : syntax error : 'public' in Qt

java - 如何根据父类计算子类的面积

c++ - 是否对未指向序列未定义行为中的元素的指针递增/递减或添加整数值?

c++ - 比较对象指针

c++ - 错误 : no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream<char>}' and 'std::vector<double>' )

c++ - 将 read() 内容传递给 C++ 字符串类型

c++ - C++中的继承(父类和子类)

c++ - 用纯虚拟覆盖虚拟..可以吗?

c - 在函数中通过指针传递字符数组