在学习侯捷的C++面向对象高级编程的时候,我发现了以下的小问题
ide是vs2017
首先创建几个有继承关系的class
class Base1 {};
class Derived1 : public Base1{};
class Base2{};
class Derived2 : public Base2{};
其次是一个pair,使用到了成员模板
template<class T1, class T2>
struct pair {
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair()
:first(T1()), second(T2()) {}
pair(const T1& a, const T2& b)
:first(a), second(b) {}
template<class U1, class U2>
pair(const pair<U1, U2> &p)
:first(p.first), second(p.second) {}
};
main函数测试
int main()
{
pair<Base1, Base2> p(pair<Derived1, Derived2>()); // 1. 常识上可以
pair<Derived1, Derived2> p2(pair<Base1, Base2>()); // 2. 常识上不行
pair<Base1, Base2> p5; // 4. 常识上不行
pair<Derived1, Derived2> p6(p5);
pair<Derived1, Derived2> p3; // 3. 常识上可以
pair<Base1, Base2> p4(p3);
std::cin.get();
}
第4种情况报错
错误为:
error C2664: ‘Derived1::Derived1(Derived1 &&)’: cannot convert argument 1 from ‘const T1’ to ‘const Derived1 &’
error C2664: ‘Derived2::Derived2(Derived2 &&)’: cannot convert argument 1 from ‘const T2’ to ‘const Derived2 &’
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
这个错误按照我的理解,应该是无法将基类转化为派生类(鱼类是鲫鱼×)?所以这个错误是正常的。
所以是否能够认为,情况2是编译器中存在的一个bug?