我创建了一个模板类Grid(我在头文件中说T的默认值是float),我引用了源文件的一部分:
#include"Grid.h"
template <class T>
Grid<T>::Grid(unsigned int rows=1, unsigned int columns=1)
:Rows(rows),Columns(columns)
{
reset();
}
template<class T>
Grid<T>::~Grid(){}
template <class T>
void Grid<T>::reset()
{
vector<T> vec(Rows * Columns,T());
matrix = vec;
}
其他成员函数可以读取/更改矩阵的值或cout它。
Grid.h:
template<typename T=float> class Grid{
public:
Grid(unsigned int, unsigned int);
~Grid();
T getValue(unsigned int, unsigned int);
void setValue(unsigned int, unsigned int, T);
void reset();
void write();
private:
unsigned int Rows;
unsigned int Columns;
vector<T> matrix;
};
我在互联网上发现,为了使用模板类,我需要#include Grid.cpp以及Grid.h,这样做我可以在main()中使用clas Grid及其成员函数。我还放了一个预处理器包装器arround Grid.cpp。
现在,当我尝试构建一个新的类PDEProblem时,没有继承但使用Grid类型的成员我得到错误:
Error 2 error C2512: 'Grid<>' : no appropriate default constructor available c:\users\... 15
Error 3 error C2512: 'Grid<T>' : no appropriate default constructor available c:\users\... 15
4 IntelliSense: no default constructor exists for class "Grid<float>" c:\Users\... 15
PDEProblem.h:
#include"grid.h"
#include"grid.cpp"
class PDEProblem: Grid<>
{
public:
PDEProblem(unsigned int,unsigned int);
~PDEProblem();
//some more other data members
private:
Grid<char> gridFlags;
Grid<> grid;
unsigned int Rows;
unsigned int Columns;
void conPot(unsigned int, unsigned int);
void conFlag(unsigned int, unsigned int);
};
PDEProblem.cpp:
#include"grid.h"
#include"grid.cpp"
#include "PDEProblem.h"
PDEProblem::PDEProblem(unsigned int rows=1,unsigned int columns=1)
:Rows(rows), Columns(columns)
{
conPot(rows, columns);
conFlag(rows,columns);
}
PDEProblem::~PDEProblem(){}
void PDEProblem::conPot(unsigned int rows, unsigned int columns)
{
grid=Grid<>(rows,columns);
}
void PDEProblem::conFlag(unsigned int rows, unsigned int columns)
{gridFlags=Grid<char>(rows,columns);
// some stuff with a few if and for loops which sets some elements of gridFlags to 1 and the others to 0
}
我该如何解决这个问题?在我看来,我有相关的一切默认值? 谢谢
答案 0 :(得分:1)
使用我的编译器(Visual Studio 2010)和您的代码,我可以通过将默认参数值从函数定义移动到函数原型来消除您的错误。具体做法是:
Grid.h
template<typename T=float> class Grid{
public:
Grid(unsigned int rows = 1, unsigned int columns = 1);
...
};
Grid.cpp
template <class T>
Grid<T>::Grid(unsigned int rows, unsigned int columns)
:Rows(rows),Columns(columns)
{
reset();
}
答案 1 :(得分:0)
您的问题是您的主类继承自Grid,同时包含另外两个Grid实例。除了糟糕的设计之外,您的两个Grid实例没有任何显式构造函数,这就是您遇到错误的原因。 设置默认值不是正确的方法。