具有非模板基类的模板类
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;
};
相关文章:
- std::具有相同基类的类的变体
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 基类中的函数名称解析
- C++初始化基类
- 如何通过派生类函数更改基类中的向量
- 如何定义一个纯抽象基类
- 如何使用基类指针引用派生类成员
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 为什么此派生对象无法访问基类的后递减方法?
- 公开最直接的基类模板名称
- 当基类是依赖类型时,这是一个缺陷吗
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- 模板基类中的静态变量
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 继承和友元函数,从基类访问受保护的成员