用templates
修改TAD
以使其成为通用(添加模板(:
对于输入/输出数据,我有此代码:
std::ostream& operator<<(std::ostream& os, Matrix & m)
{
os << m.rows() << " " << m.columns() << std::endl;
os << std::setprecision(4) << std::fixed;
for(int i=1; i <= m.rows(); i++)
{
for(int j=1; j <= m.columns(); j++)
{
os << m.value(i,j) << " ";
}
os << std::endl;
}
return os;
}
std::istream& operator>>(std::istream& is, Matrix& m)
{
int rows, columns;
float v;
is >> rows >> columns;
for (int i=1; i<=rows; i++)
{
for (int j=1; j<=columns; j++)
{
is >> v;
m.assign(i,j,v);
}
}
return is;
}
定义(摘要(:
#ifndef MATRIX_HPP
#define MATRIX_HPP
#include <stdexcept>
#include <iostream>
#include <iomanip>
template<typename E, int R, int C>
class Matriz
{
public:
Matrix();
private:
E elements_[R][C];
};
#include "matrix.cpp"
#include "matrix_io.cpp"
#endif // MATRIX_HPP
实现(摘要(:
#include <limits>
#include <cmath>
template<typename E, int R, int C>
Matrix<E,R,C>::Matrix()
{
for(int i=0; i<R; i++)
{
for(int j=0; j<C; j++)
{
elements_[i][j] = 0;
}
}
}
这是错误:
#include "matrix.hpp"
#define Element float
#define MatrixP Matrix<Element, 3, 3>
void tryBuildMatrix()
{
MatrixP m;
std::cout << m;
}
此错误:
错误:不能绑定'std :: ostream {aka std :: basic_ostream}' lvalue to'std :: basic_ostream&amp;&amp;'std :: cout&lt;&lt;m;
知道为什么会发生?
ps:如果我删除template
,则代码是完美的。
template<typename E, int R, int C>
std::ostream& operator<<(std::ostream& os, Matrix<E, R, C> & m)
{
...
}