I've just picked up C++ after years of meaning to. Right now I'm trying to implement a simple matrix class to be used from other classes. Following GManNickG's lead, here's my SimpleMatrix
(declared in "SimpleMatrix.h"):
#pragma once
#include
template
class SimpleMatrix {
unsigned int numCols, numRows;
public:
std::vector 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);
};
and implemented as (in "SimpleMatrix.cpp"):
#include "SimpleMatrix.h"
template
T SimpleMatrix::getElement(unsigned int column, unsigned int row) {
return data[row * numCols - 1];
}
template
void SimpleMatrix::setShape(unsigned int columns, unsigned int rows, const T& initValue) {
numCols = columns;
numRows = rows;
data.assign(columns * rows, initValue);
}
Now, when I use SimpleMatrix
from main
, it compiles, links and works fine. When I try to use it from an object Container
declared as (in "Container.h"):
#include "SimpleMatrix.h"
class Container {
public:
SimpleMatrix matrix;
Container();
void doStuff();
};
and implemented as (in "Container.cpp"):
#include "Container.h"
#include "SimpleMatrix.h"
void Container::doStuff() {
this->matrix.setShape(2, 2, 0);
this->matrix.getElement(1, 1);
}
Xcode complains that
Undefined symbols for architecture x86_64:
"SimpleMatrix
::getElement(unsigned int, unsigned int)", referenced from:
Container::doStuff() in Container.o
"SimpleMatrix::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)
I've checked the "Build Phases/Compile Sources"-settings, and all three files are there (main.cpp, SimpleMatrix.cpp, and Container.cpp).
There are probably a number of issues with this code. One that springs to mind is the lack of a default constructor for SimpleMatrix
, but that's not really what concerns me here. I just can't understand what the fundamental difference between the two cases is.
Any help is greatly appreciated.
Answer
Implementation of templates has to be in the header file.
No comments:
Post a Comment