C++ VS,在头文件中给出了函数声明,在另一个源文件里给出定义,main()所在源文件和上述两个文件都已包含在同一项目里,但编译时对在另一源文件中定义的函数会报错“无法解析的外部命令”,而在main函数所在源文件中include包含函数定义的源文件,则编译通过。不应该是自动链接吗?
//Matrix.h
#ifndef A
#define A
#include<iostream>
#include<vector>
using namespace std;
template<typename elemtype>
class Matrix {
public:
Matrix(elemtype seq[16])
{
vector<elemtype> a(4);
for (int ix = 0; ix < 4; ix++)
{
_elems.push_back(a);
}
int row,column;
for (int ix = 0; ix < 16; ix++)
{
row = ix / 4,column=ix%4;
_elems[row][column] = seq[ix];
}
}
Matrix()
{
vector<elemtype> a(4);
for (int ix = 0; ix < 4; ix++)
{
_elems.push_back(a);
}
}
elemtype& operator()(int row, int column)
{
return _elems[row][column];
}
elemtype operator()(int row, int column)const
{
return _elems[row][column];
}
Matrix operator+(const Matrix&)const;//
Matrix operator*(const Matrix&)const;
void print(ostream& os = cout)const;
Matrix& operator+=(const Matrix&);
private:
vector<vector<elemtype> > _elems;
};
#endif
//Matrix.cpp
#include"Matrix.h"
template<typename elemtype>
Matrix<elemtype> Matrix<elemtype>::operator*(const Matrix& rhs)const
{
Matrix new_Matrix;
int row, column;
for (int ix = 0; ix < 16; ix++)
{
row = ix / 4, column = ix % 4;
float sum = 0;
for (int ix = 0; ix < 4; ix++)
{
sum += this->_elems[row][ix] * rhs._elems[ix][column];
}
new_Matrix._elems[row][column]=sum;
}
return new_Matrix;
}
template<typename elemtype>
Matrix<elemtype> Matrix<elemtype>::operator+(const Matrix& rhs)const
{
Matrix new_Matrix;
int row, column;
for (int ix = 0; ix < 16; ix++)
{
row = ix / 4;
column = ix % 4;
new_Matrix._elems[row][column] =
this->_elems[row][column] + rhs._elems[row][column];
}
return new_Matrix;
}
template<typename elemtype>
Matrix<elemtype>& Matrix<elemtype>::operator+=(const Matrix& rhs)
{
*this = *this + rhs;
return *this;
}
template<typename elemtype>
void Matrix<elemtype>::print(ostream& os)const
{
int row, column;
for (int ix = 0; ix < 16; ix++)
{
row = ix / 4, column = ix % 4;
os << _elems[row][column] << " ";
if (column == 3)
os << '\n';
}
}
//Matrix_test.cpp
#include"Matrix.h"
using namespace std;
int main()//调用了在Matrix.cpp中定义的函数
{
...
}