2013-05-02 86 views
0

好的,我想写一个建立2D矩阵的模板,我希望>>和< <正常工作,这里是我迄今为止的代码,但是,我搞不清楚了。我现在有功能输入和输出以通过填充模板来运行用户,所以我希望能够模板和cout。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); 
} 
+0

好吧我会添加无效,我只是使用一般指针。我将这些类添加到原始帖子中。 – sdla4ever 2013-05-02 01:38:05

+0

你班上的名字是什么? – 0x499602D2 2013-05-02 01:39:49

+0

class Matrix就是我正在使用的 – sdla4ever 2013-05-02 01:41:13

回答

0

以下是我在代码中发现的所有问题。让我们从头开始:

  • 错误的函数通过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功能的循环,你这样做:

    cout << "(" << z << "," << x << ")" << "=" << this->(z, x) << endl; 
    

    this->(z, x)是不是在做你的想法。它不会同时访问矩阵的两个数据成员。由于语法无效,它实际上会导致错误。你必须分别访问这些数据成员,就像这样:

    ... << this->z << this->x << endl; 
    

    而且,这种output功能不需要返回类型。只需做到void

    请注意,您在input函数中遇到同样的问题。

+0

好的,所以我已经改变了代码,以显示我读到通过我上面给出的一些链接后得到的一切。 – sdla4ever 2013-05-02 20:38:46

相关问题