比较基类和派生类的指针
C++: Comparing pointers of base and derived classes
我想了解一些关于比较指针的最佳实践的信息,例如:
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
是虚继承的,也不能静态强制转换为D
。
在上述情况下,您不需要任何强制转换,简单的Base* b = d;
将工作。然后你可以像现在这样比较指针
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 如何使用基类指针引用派生类成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 如果基类包含双指针成员,则派生类的构造函数
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 如何在工厂方法中返回指向基于基础操作系统的派生类的有效指针
- 指向基类派生类的 std::unique_ptr 的指针
- 当我在 C++ 中将派生类的指针分配给指针时,地址会更改
- 从基指针到派生的强制转换问题
- 派生类是从基类继承 v 指针并仅使用它,还是也有自己的 v 指针?
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- 从基类指针派生派生类的模板类型
- 指向从指针派生类成员函数的指针,指向基类成员函数
- 访问通过指针派生的类
- 如果未使用虚拟函数,则使用基类指针派生类的任何目的
- 从基指针C++派生类的类型
- 无法从指针派生类转换为指针基类(多态性)
- C++ - 传递智能指针派生类