【发布时间】:2017-06-25 00:59:32
【问题描述】:
当用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}' 左值到 'std::basic_ostream&&' std::cout
知道为什么会发生吗?
PS:如果我删除template,代码就完美了。
【问题讨论】:
-
你的重载操作符也需要是模板函数,或者一些模板的实例。
-
喜欢矩阵类?
template<typename T> std<T>::istream& operator>> -
是的,您的运算符采用简单的“矩阵”参数。告诉我你在哪里定义这些?无处。您需要使用相同的模板定义才能使其工作。