C++ 模板>>和<<过载问题
C++ Template >> and << overloading trouble
好的,所以我想写一个模板,建立一个二维矩阵,我想要的>>和<<正常工作,这里是代码我有到目前为止,但我迷路了。我有输入和输出函数来运行用户填充模板,所以我希望能够查看和计算模板。
#include <iostream>
#include <cstdlib>
using namespace std;
template <typename T >
class Matrix
{
friend ostream &operator<<(ostream& os,const Matrix& mat);
friend istream &operator>>(istream& is,const Matrix& mat);
private:
int R; // row
int C; // column
T *m; // pointer to T
public:
T &operator()(int r, int c){ return m[r+c*R];}
T &operator()(T a){for(int x=0;x<a.R;x++){
for(int z=0;z<a.C;z++){
m(x,z)=a(x,z);
}
}
}
~Matrix();
Matrix(int R0, int C0){ R=R0; C=C0; m=new T[R*C]; }
void input(){
int temp;
for(int x=0;x<m.R;x++){
for(int y=0;y<m.C;y++){
cout<<x<<","<<y<<"- ";
cin>>temp;
m(x,y)=temp;
}
}
}
};
// istream &operator>>(istream& is,const Matrix& mat){
// is>>mat
// };
ostream &operator<<(ostream& os,const Matrix& mat){
for(int x=0;x<mat.R;x++){
for(int y=0;y<mat.C;y++){
cout<<"("<<x<<","<<y<<")"<<"="<<mat.operator ()(x,y);
}
}
};
int main()
{
Matrix<double> a(3,3);
a.input();
Matrix<double> b(a);
cout<<b;
cout << a(1,1);
}
以下是我在你的代码中发现的所有问题。让我们从头开始:
-
通过
this
的函数返回类型和赋值错误T operator>>(int c) { this = c; }
为什么这段代码是错误的?好吧,我注意到的第一件事是,你的函数返回
T
,但你没有返回语句存在于块。忘记我在评论中所说的,您的插入/用力操作符应该返回*this
。因此,您的返回类型应该是Maxtrix&
。我在这段代码中看到的另一个错误是您正在分配
this
指针。这不应该为您编译。相反,如果您打算更改某个数据成员(最好是您的C
数据成员),它应该看起来像这样:
接下来,你的函数应该是这样的:this->C = c;
Matrix& operator>>(int c) { this->C = c; return *this; }
-
this->(z, x)
在
output
函数的内部for循环中,您这样做:cout << "(" << z << "," << x << ")" << "=" << this->(z, x) << endl;
this->(z, x)
没有做你想的那样。它不能并发访问矩阵的两个数据成员。它实际上会因为语法无效而导致错误。您必须分别访问数据成员,像这样:... << this->z << this->x << endl;
而且,这个
output
函数不需要返回类型。就改成void
吧。请注意,您在
input
函数中有相同的问题。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中