c++ - 在 C++ 中使用模板调用派生类中父类的构造函数的正确语法是什么?
问题描述
我的类需要调用他父类的构造函数。但是我对此有疑问,因为它们是模板类。
我的派生类的代码如下:
template <class CTHIS, typename T>
class genericalMethodClassWithSeveralInternalParametersClass:public genericalMethodClassWithInternalParameterClass<CTHIS, myNUpleType<T>>
{
protected:
float (CTHIS::*funcVersionWith2Parameters)(float, myNUpleType<T>) const;
public:
genericalMethodClassWithSeveralInternalParametersClass(float (CTHIS::*_funcVersionWith2Parameters)(float, myNUpleType<T>) const, const CTHIS *_thisPar, myNUpleType<T> _fixedParam)
{
funcVersionWith2Parameters = _funcVersionWith2Parameters;
genericalMethodClassWithInternalParameterClass<CTHIS, myNUpleType<T>>::genericalMethodClassWithInternalParameterClass<CTHIS, myNUpleType<T>>(funcVersionWith2Parameters, _thisPar, _fixedParam); // compiler doesn't accept this line
}
};
构造函数的第二行应该调用父类的构造函数,但是编译器不接受它。我应该在里面放什么?
编辑:我只是在初始化列表中添加了构造函数并且它起作用了:
template <class CTHIS, typename T>
class genericalMethodClassWithSeveralInternalParametersClass:public genericalMethodClassWithInternalParameterClass<CTHIS, myNUpleType<T>>
{
protected:
float (CTHIS::*funcVersionWith2Parameters)(float, myNUpleType<T>) const;
public:
genericalMethodClassWithSeveralInternalParametersClass(float (CTHIS::*_funcVersionWith2Parameters)(float, myNUpleType<T>) const, const CTHIS *_thisPar, myNUpleType<T> _fixedParam):genericalMethodClassWithInternalParameterClass<CTHIS, myNUpleType<T>>(_funcVersionWith2Parameters, _thisPar, _fixedParam)
{
funcVersionWith2Parameters = _funcVersionWith2Parameters;
}
};
不过,对于未来,我想知道如何在派生类代码中调用父级的构造函数。实际上,想了一会儿,这个语法问题可能会出现在任何对父类的方法(不仅仅是构造函数)的调用中。
解决方案
唯一可以调用基类构造函数的地方是构造函数初始化列表:
genericalMethodClassWithSeveralInternalParametersClass(float (CTHIS::*_funcVersionWith2Paramaters)(float, myNUpleType<T>) const, const CTHIS *_thisPar, myNUpleType<T> _fixedParam)
:genericalMethodClassWithInternalParameterClass<CTHIS, myNUpleType<T>>(&_funcVersionWith2Paramaters, _thisPar, _fixedParam)
{
funcVersionWith2Paramaters = _funcVersionWith2Paramaters;
}
请注意,类的基类部分始终必须在类本身之前构造。所以不能先初始化派生类的成员,然后再去构造基类。
推荐阅读
- ruby - 增加版本的最后一部分
- spring-boot - 由于“No 'Access-Control-Allow-Header'”,CORS 阻止重定向到 localhost 页面上的 Spring OAuth 登录
- c# - 在存储库模式中使用 UnitOfWork 的困惑
- python - 如何在 PSSE 上查找/修复属性错误?
- javascript - 使用 ES6 类和 $resource 创建服务
- android - 使用 Unity3D 在 biter.jnibridge.JNIBridge.invoke 出现 java.lang.Error
- excel - 将 multipart/form-data 发布到端点
- c# - 为什么 Winform WebBrowser 从 Windows StartUp 启动 .exe 时不加载页面
- codeigniter - 将数组添加到 cookie codeigniter
- css - Angular 2 从 styles.scss 扩展样式