类模板中函数的声明与定义放在.h和.cpp中的问题

本文分析了一个关于模板类实例化时出现的链接错误,并提供了解决方案。通过在使用模板类的cpp文件中引入相应的cpp文件,成功解决了undefined reference的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天写一个模板类,用MingW翻译,出现undefined reference to `RBTreeNode<int, int>::RBTreeNode.....

RBTreeNode是一个模板类,可以见后面的代码。其声明放在了.h中,定义放在了.cpp中。

main.cpp引用BRTreeNode类的构造函数,出现Link Error.

简单分析一下:

共有三个文件RBNode.h,RBNode.cpp,main.cpp

其中RBNode.cpp include BRNode.h

main.cpp引用RBNode.h

由于main.cpp只能看见RBNode.h中的模板方法,在实例化的时候,BRNode.cpp还是undefined,因此就出现了,这个undefined reference错误,解决的方法是

main.cpp

加入#include "RBNode.cpp"即可解决这个问题

代码定义如下:

 

ContractedBlock.gifExpandedBlockStart.gifCode
//文件RBNode.h
#pragma once;
#include 
<iostream>
#include 
<list>
using namespace std;

template
<class Key,class Value>
class RBTreeNode{
public:
    RBTreeNode
<Key,Value>* parent;
    RBTreeNode
<Key,Value>* left_child;
    RBTreeNode
<Key,Value>* right_child;
    Key key;
    Value value;
    RBTreeNode(Key key,Value value,RBTreeNode
<Key,Value>* parent=NULL,RBTreeNode<Key,Value>* left_child=NULL,RBTreeNode<Key,Value>* right_child=NULL);
};

 

 

ContractedBlock.gifExpandedBlockStart.gifCode
//文件RBNode.cpp
#include "RBNode.h"

template
<class Key,class Value>
RBTreeNode
<Key,Value>::RBTreeNode(Key key,Value value,RBTreeNode<Key,Value>* parent,RBTreeNode<Key,Value>* left_child,RBTreeNode<Key,Value>* right_child){
        
this->key=key;
        
this->value=value;
        
this->parent=parent;
        
this->left_child=left_child;
        
this->right_child=right_child;
}

 

 

ContractedBlock.gifExpandedBlockStart.gifCode
//文件main.cpp

#include 
"RBNode.h"
#include 
"RBNode.cpp"
int main(){
    RBTreeNode
<int,int> root(1,1);
}

 

总结:

1.在使用以.h,.cpp分离实现模板类时,不能像使用普通类一样只简单的包涵.h头文件,应该在使用模板类的cpp文件中引入模板类相应的cpp文件
2.将模板类的声明与实现都放在.h中(在多个cpp中使用不同模板参数时可能会引起重复定义的编译错误)

转载于:https://www.cnblogs.com/CUCmehp/archive/2009/08/06/1540276.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值