相关疑难解决方法(0)

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

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

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

为什么是这样?

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

c++ templates c++-faq

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

.c vs .cc vs. .cpp vs .hpp vs .h vs .cxx

可能的重复:
*.h或*.hpp为您的类定义
正确的C++代码文件扩展名?.cc vs .cpp

我曾经认为过去是这样的:

  • .h 文件是C和C++的头文件,通常只包含声明.
  • .c 文件是C源代码.
  • .cpp 文件是C++源代码(也可以是C源代码).

那些文件就像.hpp,.cc然后.cxx出现了,我完全糊涂了......那些之间的区别是什么?你什么时候使用"新"的?

c c++

221
推荐指数
6
解决办法
16万
查看次数

如何在模板类之外定义构造函数

如果我在类之外定义模板类的构造函数\析构函数,则会出现链接器错误。难道不允许吗?我使用 Visual Studio 2010。

错误 1>main.obj : 错误 LNK2019: 函数 _main 中引用了无法解析的外部符号“public: __thiscall Tree::~Tree(void)” (??1?$Tree@H@@QAE@XZ)

1>main.obj : 错误 LNK2019: 函数 _main 中引用了无法解析的外部符号“public: __thiscall Tree::Tree(void)” (??0?$Tree@H@@QAE@XZ)

在.h文件中

template <class T>
class Tree{
public:
    Tree(void);
    ~Tree(void);
    T x;
};
Run Code Online (Sandbox Code Playgroud)

在 .cpp 文件中

#include "Tree.h"

template <class T> Tree<T>::Tree(void){
}

template <class T> Tree<T>::~Tree(void){
}
Run Code Online (Sandbox Code Playgroud)

在main.cpp文件中

#include "Tree.h"
int main(){
    Tree<int> t;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ constructor

8
推荐指数
1
解决办法
1万
查看次数

标签 统计

c++ ×3

c ×1

c++-faq ×1

constructor ×1

templates ×1