#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*>
发布于 2010-01-26 12:04:14
std::pair有一个构造函数模板:
template<class U, class V> pair(const pair<U, V> &p);“效果:从相应的参数成员初始化成员,根据需要执行隐式转换。”(C++03,20.2.2/4)
从派生类指针到基类指针的转换是隐式的。
发布于 2010-01-26 12:08:53
因为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)https://stackoverflow.com/questions/2137441
复制相似问题