C++ 模板>>和<<过载问题

C++ Template >> and << overloading trouble

本文关键字:lt gt 问题 C++ 模板      更新时间:2023-10-16

好的,所以我想写一个模板,建立一个二维矩阵,我想要的>>和<<正常工作,这里是代码我有到目前为止,但我迷路了。我有输入和输出函数来运行用户填充模板,所以我希望能够查看和计算模板。

#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函数中有相同的问题。