c++ - 无法理解为什么 XCode 链接器看不到某些方法

标签 c++ linker-errors

<分区>

经过多年的学习,我刚刚学会了 C++。现在我正在尝试实现一个简单的矩阵类以供其他类使用。正在关注GManNickG's lead ,这是我的 SimpleMatrix(在“SimpleMatrix.h”中声明):

#pragma once
#include <vector>

template <typename T>
class SimpleMatrix {    
    unsigned int numCols, numRows;    
public:    
    std::vector<T> data;

    SimpleMatrix(unsigned int cols, unsigned int rows) :
    numCols(cols),
    numRows(rows),
    data(numCols * numRows)
    {};

    T getElement(unsigned int column, unsigned int row);
    void setShape(unsigned int column, unsigned int row, const T& initValue);    
};

并实现为(在“SimpleMatrix.cpp”中):

#include "SimpleMatrix.h"

template <class T>
T SimpleMatrix<T>::getElement(unsigned int column, unsigned int row) {   
    return data[row * numCols - 1];    
}

template <class T>
void SimpleMatrix<T>::setShape(unsigned int columns, unsigned int rows, const T& initValue) {
    numCols = columns;
    numRows = rows;
    data.assign(columns * rows, initValue);
}

现在,当我使用 main 中的 SimpleMatrix 时,它会编译、链接并正常工作。当我尝试从声明为(在“Container.h”中)的对象 Container 中使用它时:

#include "SimpleMatrix.h"

class Container {
public:    
    SimpleMatrix<int> matrix;    
    Container();    
    void doStuff();
};

并实现为(在“Container.cpp”中):

#include "Container.h"
#include "SimpleMatrix.h"

void Container::doStuff() {    
    this->matrix.setShape(2, 2, 0);
    this->matrix.getElement(1, 1);
}

Xcode 提示说

Undefined symbols for architecture x86_64:

"SimpleMatrix<int>::getElement(unsigned int, unsigned int)", referenced from:
Container::doStuff() in Container.o   

"SimpleMatrix<int>::setShape(unsigned int, unsigned int, int const&)", referenced from:
Container::doStuff() in Container.o 

ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

我检查了“Build Phases/Compile Sources”设置,所有三个文件都在那里(main.cpp、SimpleMatrix.cpp 和 Container.cpp)。

此代码可能存在许多问题。我突然想到的是 SimpleMatrix 缺少默认构造函数,但这并不是我真正关心的问题。我只是不明白这两种情况之间的根本区别是什么。

非常感谢任何帮助。

最佳答案

模板的实现必须在头文件中。

关于c++ - 无法理解为什么 XCode 链接器看不到某些方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15012141/

相关文章:

c++ - VS2010上的Boost Log链接错误

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 错误: LINK2019: unresolved external symbol when using operator << in a namespace

c++ - 在 C++ 中,使用 #define 还是 const 来避免魔数(Magic Number)更好?

c++ - 0x7A47E727中未处理的异常

c++ - 澄清想要重新。 C++ 类型特征

c++ - 在 Linux 中编译基本 QtWidgets 应用程序时出现 QtCreator 问题

c++ - 使用可变参数模板调用成员函数

c - 在 GCC 中使用 -Wall -Wextra 并出现错误

c++ - .mm 测试文件的 OCMock 3.0.2 链接器错误