相关疑难解决方法(0)

为什么模板只能在头文件中实现?

引自C++标准库:教程和手册:

目前使用模板的唯一可移植方法是使用内联函数在头文件中实现它们.

为什么是这样?

(澄清:头文件不是唯一的便携式解决方案.但它们是最方便的便携式解决方案.)

c++ templates c++-faq

1660
推荐指数
14
解决办法
46万
查看次数

"对模板类构造函数的未定义引用

我不知道为什么会发生这种情况,因为我认为我已经正确地声明和定义了所有内容.

我有以下程序,使用模板设计.这是一个简单的队列实现,其成员函数为"add","substract"和"print".

我已经在精细的"nodo_colaypila.h"中为队列定义了节点:

#ifndef NODO_COLAYPILA_H
#define NODO_COLAYPILA_H

#include <iostream>

template <class T> class cola;

template <class T> class nodo_colaypila
{
        T elem;
        nodo_colaypila<T>* sig;
        friend class cola<T>;
    public:
        nodo_colaypila(T, nodo_colaypila<T>*);

};
Run Code Online (Sandbox Code Playgroud)

然后在"nodo_colaypila.cpp"中实现

#include "nodo_colaypila.h"
#include <iostream>

template <class T> nodo_colaypila<T>::nodo_colaypila(T a, nodo_colaypila<T>* siguiente = NULL)
{
    elem = a;
    sig = siguiente;//ctor
}
Run Code Online (Sandbox Code Playgroud)

然后,队列模板类的定义和声明及其功能:

"cola.h":

#ifndef COLA_H
#define COLA_H

#include "nodo_colaypila.h"

template <class T> class cola
{
        nodo_colaypila<T>* ult, pri;
    public:
        cola<T>();
        void anade(T&);
        T saca();
        void print() const;
        virtual …
Run Code Online (Sandbox Code Playgroud)

c++ templates compiler-errors codeblocks

136
推荐指数
3
解决办法
11万
查看次数

标签 统计

c++ ×2

templates ×2

c++-faq ×1

codeblocks ×1

compiler-errors ×1