首先,前向声明 Matrix 类。这允许 Iterator 类查看 Matrix 类的名称,并对其进行指针和引用。(它还不允许 Iterator 类访问成员数据或调用成员函数。)
template<typename T, typename Size, typename Stack, typename Sparse>
class Matrix;
然后,定义 Iterator 类。此时它所能做的就是保存对矩阵的引用和指针。(还不能访问 Matrix 的成员。)
template<typename T, typename Size>
class Iterator{
// don't define any function bodies in here
//but do put all data members and prototypes in here
};
然后定义Matrix类(可以访问Iterator成员)
template<typename T, typename Size, typename Stack, typename Sparse>
class Matrix{
// don't define any function bodies in here
//but do put all data members and prototypes in here
};
然后为每个类定义方法体。此时,两个类的方法都可以访问彼此的成员。通常,这部分放在 .cpp 文件中,但对于模板,它属于 .h 文件。
template<typename T, typename Size, typename Stack, typename Sparse>
Matrix<T,Size,Stack,Sparse>::Matrix(){ /*...*/}
template<typename T, typename Size>
Iterator<T,Size>::Iterator(){ /*...*/ }