2012-11-22 109 views
1

我要创建一个矩阵类,我得到了一些问题,超负荷运营商我怎么能重载<<操作

我想用<<操作

Matrix<double> u3(2,2); 

u3 << 3.3, 4, 3, 6; 


template<class T> 
Matrix<T> Matrix<T>::operator <<(T in){ 
    //Fill up the matrix, m[0] = 3.3, m[1]=4... 
    return *this; 
} 
填写一份矩阵

这个操作符如何过载?

+0

did you mean:overload – Kos

+0

而在这种情况下,您有两个要重载的运算符:'<<'和','。 – Kos

+0

填写或打印出来? – 2012-11-22 10:57:30

回答

3

下面是一个使用逗号的方法:

#include <iostream> 
using namespace std; 

struct Matrix { 

    struct Adder { 
     Matrix& m; 
     int index; 

     Adder(Matrix& m) : m(m), index(1) {} 

     Adder& operator,(float value) { 
      m.set(index++, value); 
      return *this; 
     }  
    }; 

    void set(int index, float value) { 
     // Assign value to position `index` here. 
     // I'm just printing stuff to show you what would happen... 
     cout << "Matrix[" << index << "] = " << value << endl; 
    } 

    Adder operator<<(float value) { 
     set(0, value); 
     return Adder(*this); 
    } 

}; 

演示:http://ideone.com/W75LaH

几点说明:

语法matrix << 5, 10, 15, 20分两步实现:

  • matrix << 5先求;它将第一个元素设置为5并返回处理进一步插入的临时对象Adder已重载operator,在每个逗号后执行以下插入。
+0

我假设你知道如何将它变成模板并处理更多维度。如果您需要进一步的帮助,请留下评论,我会扩大。 – Kos

+0

谢谢你的想法。我还有一个问题,我超载了'Matrix * scalar',但是我怎么能超载'标量*矩阵'操作? –

+0

轻松;使重载操作符成为常规的2参数函数,而不是1参数成员函数。 – Kos

1

像这样的方法是有效的:

#include <iostream> 


template <typename T> 
class Mat { 
public: 
    T val; 
}; 

template <typename T> 
Mat<T>& operator<<(Mat<T>& v, T in) { 
    std::cout << in << " "; 
    return v; 
} 

int main() { 
    Mat<int> m; 
    m << 1 << 2 << 3; 
} 

请注意,我使用的是免费operator<<功能,并且不使用的值之间的逗号。

+0

这种方法也可以工作,但它需要'Mat'有一个额外的计数器变量来记住插入之间的索引。而且你需要像使用特殊标记的另一个'operator <<'重载,以便能够在几个不同的赋值序列之间重置该索引。 0现在,如果你完成它将变为+1 :-) – Kos

+0

@Kos你可以通过用nan填充矩阵并填充一个nan运算符<<(不是最优的,我知道但是很简单)来实现这个。我没有看到他希望我们填写内部函数的问题,他只是想让超载正确。 – daramarak