C++比较不同类型的指针

C++ comparing pointers to different types?

本文关键字:指针 同类型 比较 C++      更新时间:2023-10-16

我很难找到关于这类东西的信息!:(

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

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

这里有一个简单的例子,说明您的要求不起作用。

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

将失败。

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

如果你想检查你是否没有调用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,则会出现编译器错误。