template < class T1, class T2 >
class A
{
T1 x;
T2 y;
public:
A(T1 a, T2 b)
{
x = a;
y = b;
cout << x << " " << y << endl;
}
A(T2 b, T1 a)
{
x = a;
y = b;
cout << x << " " << y << endl;
}
};
int main()
{
A<int, float> obj1(1, 2.5);
A<float, int> obj2(1, 2.5);
return 0;
}
明白为什么obj1调用了第一个构造函数,但是obj2实例化的时候为什么调用了第二个构造函数?
最佳答案
因为T1
和T2
分别是float
和int
,所以构造函数看起来像
A (float a, int b ) // first
A (int a, float b ) // second
构造函数参数分别是int
和double
。第二个构造函数提供了比第一个更好的匹配。
关于c++ - 类模板 : Order of Construction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24838129/