我很难找到有关此类内容的信息! :(
我很困惑为什么这不起作用:
vector<B*> b;
vector<C*> c;
(B and C are subclasses of A)
(both are also initialized and contain elements etc etc...)
template <class First, class Second>
bool func(vector<First*>* vector1, vector<Second*>* vector2)
return vector1 == vector2;
编译时返回:
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
我不明白为什么这行不通,指针保存地址是吗?那么为什么不直接比较两个 vector 指针是否...指向相同的地址(-es)呢?
最佳答案
这是一个简单的示例,其中您的要求不起作用。
struct A{ int i; };
struct OhNoes { double d; };
struct B: public A {};
struct C: public OhNoes, public B {};
所以在这里,B和C都是A的子类。
但是,C
的实例不太可能与其 B
子对象具有相同的地址。
也就是这个:
C c;
B *b = &c; // valid upcast
assert(static_cast<void*>(b) == static_cast<void *>(&c));
会失败。
关于C++ 比较指向不同类型的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18126123/