【问题标题】:Error with 'ostream' and 'istream' in C++ trying to overloading尝试重载的 C++ 中的“ostream”和“istream”出错
【发布时间】: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&lt;typename T&gt; std&lt;T&gt;::istream&amp; operator&gt;&gt;
  • 是的,您的运算符采用简单的“矩阵”参数。告诉我你在哪里定义这些?无处。您需要使用相同的模板定义才能使其工作。

标签: c++ c++11 templates


【解决方案1】:
template<typename E, int R, int C>
std::ostream& operator<<(std::ostream& os, Matrix<E, R, C> & m)
{
...
}

【讨论】:

  • 这给了我另一个错误:` undefined reference to Matrix&lt;float, 3, 3&gt;::columns()'
  • 我希望您在声明 Matrix 类后声明了自定义运算符...上面的流程没有这样做,但您的代码可能会有所不同。而且,我没有看到 rows() 或 columns() 方法的定义。
  • 如果你愿意,我可以编辑问题以放置所有代码
  • 我在这里并不是真正的新人堆栈溢出西班牙语:)
猜你喜欢
  • 2020-02-10
  • 1970-01-01
  • 2016-07-28
  • 2013-10-10
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
相关资源
最近更新 更多