具有非模板基类的模板类

Template class with a non template base class

本文关键字:基类      更新时间:2023-10-16

我想知道产生此错误的确切编译器行为。

看看这个代码。

class Base_class
{
public:
  Base_class();
};
Base_class::Base_class()
{
  //Here it says multiple definitions (If I define the contructor outside)
  //If I define this inside class no error 
  //Or if I make the base class templated no error
  //Also if this is in .cpp it works.
}
template<typename T>
class Temp_derived_class:Base_class
{
public:
  Temp_derived_class();
  int *i;
};
template<typename T>
Temp_derived_class<T>::Temp_derived_class()
{
  i = new int[5];
}

这里有多个定义(如果我在外面定义构造函数)如果我在类内部定义这个,没有错误或者,如果我使基类模板化,则没有错误同样,如果这是.cpp中的,它也可以工作。

干杯,CB

所有使用的函数在程序中必须只有一个定义,或者是内联的。通过在头中放入非内联定义,通常会得到多个定义,这是一个错误。

您可以:

  • 声明构造函数inline,或
  • 将定义移动到源文件中,或者
  • 将定义移动到类定义中

函数模板和类定义中定义的成员函数是隐式内联的,这就是为什么类模板的构造函数没有类似的问题。

当您将函数定义放入标头中时,包含该标头的每个转换单元都会获得自己的函数定义。一个定义规则规定,在整个程序中,每个名称最多只能有一个定义。

不过也有例外。在函数的情况下,如果函数被标记为inline,并且所有定义都由相同的令牌序列组成,则可以有更多的定义。类内部定义的成员函数是隐式内联的,模板也是如此。

因此,除了您已经找到的解决方法外,您还可以内联标记构造函数:

inline Base_class::Base_class()
{
}

具有非模板基类的模板类应该内联编写,以避免编译器混淆。所有的核心逻辑都应该在基类中,而模板只是为了让铸造更容易。

template<typename T>
class Temp_derived_class:Base_class
{
public:
    Temp_derived_class()
    {
      i = new int[5];
    }
  int *i;
};