读书人

关于stl pair构造

发布时间: 2012-09-17 12:06:51 作者: rapoo

关于stl pair结构
各位大大好,今天看了stl pair结构,有点不解,特向大家请教下。
// TEMPLATE STRUCT pair
template<class _Ty1,
class _Ty2> struct pair
{
// store a pair of values
typedef pair<_Ty1, _Ty2> _Myt;
typedef _Ty1 first_type;
typedef _Ty2 second_type;

pair()
: first(_Ty1()), second(_Ty2())
{ // construct from defaults
}

pair(const _Ty1& _Val1, const _Ty2& _Val2)
: first(_Val1), second(_Val2)
{ // construct from specified values
}

template<class _Other1,
class _Other2>
pair(const pair<_Other1, _Other2>& _Right)
: first(_Right.first), second(_Right.second)
{ // construct from compatible pair
}

void swap(_Myt& _Right)
{ // exchange contents with _Right
std::swap(first, _Right.first);
std::swap(second, _Right.second);
}

_Ty1 first; // the first stored value
_Ty2 second; // the second stored value
};

请看这句:
pair()
: first(_Ty1()), second(_Ty2())
{ // construct from defaults
}
first(_Ty1())和second(_Ty2())这两句是什么意思啊?
我原来理解成把first初始化为_Ty1()临时对象,而这个临时对象只会调用类_Ty1的默认构造函数。
但是做了如下测试:
//例1
int i=int();
cout<<i;
此时输出0。
//例2
int i
cout<<i;
此时程序运行出错,提示Debug error!
如果int()只是调用默认构造函数的话,那么它运行的结果应该和例2一样的,所以看来我的理解是错的。
请各位大大不吝赐教,小弟不胜感激。

[解决办法]

探讨
呵呵,那大家都说说,为什么pair的构造函数要调用 first(_Ty1()), second(_Ty2())啊?
pair()
: first(_Ty1()), second(_Ty2())
{ // construct from defaults
}
first(_Ty1())是什么意思呀?

读书人网 >C++

热点推荐