I want to include my own header file but vector< vector < float > > throws an error
matrix.cpp
#include <vector>
class Matrix
{
public:
std::vector<std::vector<float>> data;
Matrix(std::vector<std::vector<float>> d_data = { {} })
{
data = d_data;
}
};
matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
class Matrix {
public:
std::vector<std::vector<float>> data;
Matrix(std::vector<std::vector<float>> d_data = { {} });
};
#endif
matrixc .cpp
#include <C:\Users\Matteo\source\repos\matrixc \matrixc \Matrix.h>
#include <vector>
int main()
{
Matrix abc({{1,2},{2,1}});
return 0;
}
Following error occurs :
matrixc .obj : error LNK2019: unresolved external symbol "public: __cdecl Matrix::Matrix(class std::vector<class std::vector<float,class std::allocator >,class std::allocator<class std::vector<float,class std::allocator > > >)" (??0Matrix@@QEAA@V?$vector@V?$vector@MV?$allocator@M@std@@@std@@V?$allocator@V?$vector@MV?$allocator@M@std@@@std@@@2@@std@@@Z) referenced in function main
CodePudding user response:
The problem is that you've more or less copy pasted the class definition to the source file matrix.cpp
. That is, you have defined the class Matrix
twice. Once in the header and second time in the source file.
To solve this just provide the implementation for the constructor Matrix::Matrix(std::vector<std::vector<float>>)
inside the source file as shown below:
matrix.cpp
#include <C:\Users\Matteo\source\repos\matrixc \matrixc \Matrix.h>
//implement only the constructor
Matrix::Matrix(std::vector<std::vector<float>> d_data): data(d_data)
^^^^^^^^^^^^ use constructor initializer list
{
}
matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <vector>
class Matrix {
public:
std::vector<std::vector<float>> data;
Matrix(std::vector<std::vector<float>> d_data = { {} });
};
#endif