C++比较不同类型的指针
C++ comparing pointers to different types?
我很难找到关于这类东西的信息!:(
我很困惑为什么这不起作用:
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,则会出现编译器错误。
相关文章:
- 接收和返回函数指针的函数指针的类型?
- 推断指针非类型模板参数的类型
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 专门C++使用指针值类型的通用迭代器的模板函数?
- 在C++中,为什么需要提及指针的类型?
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 指针数据类型变量如何包含对象?
- memcpy是否取决于源指针和目标指针的类型
- 指向 2D 数组的指针的类型是什么?
- 如何在 c++ 中实现指针的类型
- 为什么要为指针返回类型返回一系列字符?
- 如何安全地更改指针的类型
- C++中的 vptr(虚拟指针)类型
- 为什么您必须为指针指定类型
- 如何为指针创建类型定义
- 从弱指针返回类型返回共享指针
- C 不能将带有父类指针作为类型的静态模板成员定义引用
- 表达式必须在C 中具有指针对象类型
- 下标需要数组或指针类型表达式必须具有指针对象类型
- const自动参考绑定到(NULL)指针 - 实际类型是什么