【问题标题】:C++ Template >> and << overloading troubleC++ 模板 >> 和 << 重载问题
【发布时间】:2013-05-02 01:27:14
【问题描述】:

好的,所以我正在尝试编写一个构建 2D 矩阵的模板,我希望 >> 和

#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);
}

【问题讨论】:

  • 好的,我将添加 void,我只使用通用指针。我将课程添加到原始帖子中。
  • 你的班级叫什么名字?
  • 类矩阵是我正在使用的
  • 正常工作是什么意思?重载这些运算符时有quiteafewtutiorals。我建议咨询一个,因为这看起来不像通常的重载流操作符的方式。
  • 谢谢@DavidBrown,我现在就去读。我对重载运算符感到生疏。

标签: c++ templates operator-overloading


【解决方案1】:

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

  • 错误的函数返回类型和通过this赋值

    T operator>>(int c)
    {
        this = c;
    }
    

    为什么这段代码是错误的?嗯,我注意到的第一件事是你的函数正在返回T,但你在块中没有返回语句。忘记我在 cmets 中所说的话,您的插入/使用运算符应该返回 *this。因此你的返回类型应该是Maxtrix&amp;

    我在这个 sn-p 中看到的另一个错误是您正在分配 this 指针。这不应该为你编译。相反,如果您打算更改某个数据成员(最好是您的 C 数据成员),它应该看起来像这样:

    this->C = c;
    

    反过来,你的函数应该是这样的:

    Matrix& operator>>(int c)
    {
        this->C = c;
        return *this;
    }
    
  • this-&gt;(z, x)

    output 函数的内部 for 循环中,您执行了以下操作:

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

    this-&gt;(z, x) 没有按照你的想法做。它不会同时访问矩阵的两个数据成员。由于语法无效,它实际上会导致错误。您必须单独访问数据成员,如下所示:

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

    此外,这个output 函数不需要返回类型。就让它void

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

【讨论】:

  • 好的,所以我已经更改了代码以显示我通过上面给出的一些链接阅读后得到的所有内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 2011-06-11
  • 1970-01-01
相关资源
最近更新 更多