首页 > 解决方案 > 在 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;
            }
};

不过,对于未来,我想知道如何在派生类代码中调用父级的构造函数。实际上,想了一会儿,这个语法问题可能会出现在任何对父类的方法(不仅仅是构造函数)的调用中。

标签: c++templates

解决方案


唯一可以调用基类构造函数的地方是构造函数初始化列表

genericalMethodClassWithSeveralInternalParametersClass(float (CTHIS::*_funcVersionWith2Paramaters)(float, myNUpleType<T>) const, const CTHIS *_thisPar, myNUpleType<T> _fixedParam)
        :genericalMethodClassWithInternalParameterClass<CTHIS, myNUpleType<T>>(&_funcVersionWith2Paramaters, _thisPar, _fixedParam)
            {
                funcVersionWith2Paramaters = _funcVersionWith2Paramaters;   
            }

Godbolt 上的示例

请注意,类的基类部分始终必须在类本身之前构造。所以不能先初始化派生类的成员,然后再去构造基类。


推荐阅读