從我對C++繼承的理解中可以看出,每當調用子類的構造函數時,父類的構造函數都會自動調用。至於模板化構造函數,模板參數的數據類型會自動傳遞,即我們不需要單獨指定模板參數。該程序生成一個編譯錯誤,我似乎不明白。產生C++繼承類的模板構造函數
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&’
#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;
}
編譯錯誤,我不知道這裏發生了什麼。有任何想法嗎?
http://stackoverflow.com/questions/347358/inheriting-constructors –