C++ 继承类的模板构造函数
C++ Template constructor of a inherited class
根据我对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;
}
生成的编译错误
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&’
我不知道这里发生了什么。有什么想法吗?
>D
必须将构造函数参数传递给C
,因为您没有使用默认构造函数。
class D : public C {
public:
template <typename T> D (T t) : C(t) {}
float area () { /* ... */ }
};
此错误的原因是您尝试使用参数构造D
,但尚未声明任何允许您这样做的构造函数。此外,你必须将参数传递给C
,否则编译器将使用C
的默认构造函数。
编译器错误消息可以像这样分析。
test.cpp:56:8: error: no matching function for call to ‘D::D(A&)’
编译器抱怨:
D d(a);
并且当传递 A
类型的东西时,它无法弄清楚如何构造D
.
然后,它提供了它所知道的构造函数的两个选择:
test.cpp:44:7: note: D::D()
test.cpp:44:7: note: D::D(const D&)
它指出,对于每一个,都有一个原因不能使用它。对于第一个,它不需要任何参数。对于第二个,它无法将 A
类型的东西转换为 D
型 .
根据我对C++继承的理解,每当调用子类的构造函数时,都会自动调用父类的构造函数。
注意:使用与子类的构造函数相同的参数自动调用父类的构造函数。
至于手头的具体问题:没有为类 D 声明构造函数。你将获得一个默认构造函数,并将构造函数作为免费赠品,但不会获得类 C 中基于模板的构造函数。
相关文章:
- 具有相同名称的类的构造函数继承
- 多复制构造函数继承中的惊人行为
- CRTP 和复制/移动赋值/构造函数继承
- 复制构造函数继承动态分配的数组
- 无法从 c++ 中的构造函数继承
- 在构造函数继承中使用默认构造函数
- 构造函数继承和直接成员初始化
- C++ - 使用私有参数的构造函数继承
- 通过可变参数模板进行C++11构造函数继承
- C++11构造函数继承和不带参数的构造函数
- C++11 - 构造函数继承
- C++构造函数继承
- 使用 C++11 编译器的构造函数继承正在生成错误
- 选择性构造函数继承"Ambiguous resolution"错误
- 什么是构造函数继承
- C++对象中的构造函数继承与方法继承
- C++构造函数继承没有匹配的函数
- C++构造函数继承(从派生类调用构造函数)
- 模板构造函数继承的标准符合语法是什么
- C++构造函数继承错误