5

我很难找到有关这些东西的信息!:(

我很困惑为什么这不起作用:

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

我不明白为什么这不起作用,指针保存地址是吗?那么为什么不比较两个向量指针...是否指向相同的地址(-es)?

4

2 回答 2

7

这是一个简单的示例,您要求的内容不起作用。

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));

将失败。

于 2013-08-08T12:37:47.357 回答
4

您的两个向量是不同的类型,您无法比较它们。

如果你想检查你没有调用 func(b, b) 那么你可以尝试:

template <typename T> bool func(vector<T> const & a, vector<T> const & b)
{
if (&a == &b) return false;
// do stuff
return true;
}

除非你在做一些非常奇怪的事情,否则指向不同类型的两个向量的指针将不相等。如果您尝试使用两个不同类型的向量调用 func,那么您将收到编译器错误。

于 2013-08-08T12:53:41.907 回答