相关疑难解决方法(0)

使用模板时,为什么会出现"未解析的外部符号"错误?

当我使用模板为类编写C++代码并在源(CPP)文件和标题(H)文件之间拆分代码时,在链接最终可执行文件时会出现大量"未解析的外部符号"错误,尽管目标文件正确构建并包含在链接中.这里发生了什么,我该如何解决?

c++ linker templates

92
推荐指数
2
解决办法
6万
查看次数

对类模板的成员函数的未定义引用

我想在模板类方法中使用迭代器.这是我的代码:(testclass.h)

template<typename T, typename container>
class TestClassX
{
public:
    void gen(typename container::iterator first );
};
Run Code Online (Sandbox Code Playgroud)

和文件testclass.cpp:

template<typename T, typename container>
void TestClassX<T, container>::gen(typename container::iterator first)
{

}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时:

TestClassX<unsigned, std::vector<unsigned> > testx;
testx.gen(it);
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

Error:undefined reference to `TestClassX<unsigned int, std::vector<unsigned int, std::allocator<unsigned int> > >::gen(__gnu_cxx::__normal_iterator<unsigned int*, std::vector<unsigned int, std::allocator<unsigned int> > >)'
Run Code Online (Sandbox Code Playgroud)

我用的是mingw32 4.4

我想有一个类可以写入不同的容器,如std :: vector,std :: list,QVector或QList都有STL样式的迭代器.

c++ containers templates stl

7
推荐指数
1
解决办法
4671
查看次数

模板成员的奇怪"未定义引用"

首先,我知道必须在头文件中实现定义,这就是我通常根据这个线程所做的

我有几个文件

// Image.h
namespace library
{
    namespace data
    {
        template<class Pixel, class SubPixel, int Layer>
        class Image 
        {
            public:
            Image(int width, int height, Pixel emptyFill);
            Image(int width, int height);
            ~Image();

            Pixel& operator() (int x, int y);
            const Pixel& operator() (int x, int y) const;
            SubPixel& operator() (int x, int y, int subpixel);
            const SubPixel& operator() (int x, int y, int subpixel) const;

            protected:
            int m_width;
            int m_height;

            Pixel* m_pixels;
            void init(Pixel emptyFill);
            bool checkBounds(int x, int y, …
Run Code Online (Sandbox Code Playgroud)

c++ linker templates

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

C++未定义的模板类方法引用

我总是得到

未定义的引用`Graph :: InsertVertex(std :: string)'

如果我编译我的项目!有什么提示他为什么不能解决这个问题?(所有文件都在netbeans项目文件夹中)

// main.cpp

#include <cstdlib>
#include <string>
#include "Graph.h"

using namespace std;

int main(int argc, char** argv)
{
    Graph<string> *graph = new Graph<string>(); // <--- ERROR

    graph->InsertVertex("A");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

// Node.h

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

template<class T> 
class Node
{   

friend class Graph;    

public:
    Node(T val)
    {
        this->data = val;
        this->vertList = NULL;
        this->next = NULL;
    }

    Node(const Node& orig);
    virtual ~Node();

private:
    T data;
    Node<T> *vertList;
    Node<T> *next;
    int status;

};
Run Code Online (Sandbox Code Playgroud)

// …

c++ templates undefined-reference

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

标签 统计

c++ ×4

templates ×4

linker ×2

containers ×1

stl ×1

undefined-reference ×1