5
#include <vector>

struct A {int a;};
struct B : public A {char b;};

int main()
{
  B b;
  typedef std::pair<A*, A*> MyPair;
  std::vector<MyPair> v;
  v.push_back(std::make_pair(&b, &b)); //compiler error should be here(pair<B*,B*>)
  return 0;
}

我不明白为什么会这样编译(也许有人可以提供详细的解释?它与名称查找有关吗?

顺便说一句,在 Solaris 上,SunStudio12 无法编译:error : formal argument x of type const std::pair<A*, A*> & in call to std::vector<std::pair<A*,A*> >::push_back(const std::pair<A*, A*> & ) is being passed std::pair<B*, B*>

4

2 回答 2

13

std::pair有一个构造函数模板:

template<class U, class V> pair(const pair<U, V> &p);

“效果:从参数的相应成员初始化成员,根据需要执行隐式转换。” (C++03, 20.2.2/4)

从派生类指针到基类指针的转换是隐式的。

于 2010-01-26T04:04:13.617 回答
0

因为 B 是从 A 派生的,所以向量 v 将包含指向对象 b 的基类结构的指针。因此,您可以访问 A 的成员,即

std::cout << v[0].first->a;

编辑:我的错误,如下所述,您仍然可以转换为 B 类型的指针,因为向量是指针,而不是对象,因此没有发生对象切片。

一个电话如

std::cout << v[0].first->b; 

不会编译,因为向量中的元素是基类指针,并且不能在没有强制转换的情况下指向派生类成员,即

 std::cout << static_cast<B*>(v[0].first)->b; 

另请注意,动态转换,如

std::cout << dynamic_cast<B*>(v[0].first)->b;  

不会在 gcc 中编译并出现以下错误:

cast.cpp:14: error: cannot dynamic_cast ‘v.std::vector<_Tp, _Alloc>::operator[] [with _Tp = std::pair<A*, A*>, _Alloc = std::allocator<std::pair<A*, A*> >](0u)->std::pair<A*, A*>::first’ (of type struct A*’) to type struct B*’ (source type is not polymorphic)
于 2010-01-26T04:08:52.500 回答