gib*_*tar 4 c++ inheritance templates constructor
根据我对C++继承的理解,无论何时调用子类的构造函数,都会自动调用父类的构造函数.对于模板化构造函数,模板参数的数据类型会自动进行,即我们不需要单独指定模板参数.该程序生成一个我似乎不理解的编译错误.
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
class A{
public:
int x;
int y;
int first(){
return x;
}
int second(){
return y;
}
};
class C{
public:
float a,b;
C(){
a = 0.0f;
b = 0.0f;
}
template<class T>
C(T t){
a = t.first();
b = t.second();
}
};
class D: public C{
public:
float area(){
return a*b;
}
}
int main(){
A a;
a.x = 6;
a.y = 8;
C c(a);
D d(a);
cout<<c.a<<" "<<c.b<<" "<<d.area()<<endl;
}
Run Code Online (Sandbox Code Playgroud)
生成编译错误
test.cpp: In function ‘int main()’:
test.cpp:56:8: error: no matching function for call to ‘D::D(A&)’
test.cpp:56:8: note: candidates are:
test.cpp:44:7: note: D::D()
test.cpp:44:7: note: candidate expects 0 arguments, 1 provided
test.cpp:44:7: note: D::D(const D&)
test.cpp:44:7: note: no known conversion for argument 1 from ‘A’ to ‘const D&’
Run Code Online (Sandbox Code Playgroud)
我不知道这里发生了什么.有任何想法吗?
D
必须传递构造函数参数C
,因为您没有使用默认构造函数.
class D : public C {
public:
template <typename T> D (T t) : C(t) {}
float area () { /* ... */ }
};
Run Code Online (Sandbox Code Playgroud)
出错的原因是您尝试D
使用参数进行构造,但尚未声明任何允许您这样做的构造函数.此外,您必须将参数传递给C
,否则编译器将使用C
默认构造函数.
可以像这样分析编译器错误消息.
test.cpp:56:8: error: no matching function for call to ‘D::D(A&)’
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
D d(a);
Run Code Online (Sandbox Code Playgroud)
并且它无法弄清楚如何构造一个D
传递类型的东西A
.
然后介绍它知道的两个构造函数选择:
test.cpp:44:7: note: D::D()
test.cpp:44:7: note: D::D(const D&)
Run Code Online (Sandbox Code Playgroud)
并且它指出,对于每一个,有一个原因它不能使用它.对于第一个,它不需要任何参数.对于第二个,它无法将类型A
转换为类型D
.