简体   繁体   English

我怎样才能重载<<运算符

[英]How can I overload the << operator

I have to create a Matrix class, and I got some problem to overload the operators 我必须创建一个Matrix类,我有一些问题要重载运算符

I would like to fill up a matrices using the << operator 我想用<<运算符填充矩阵

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

How overload this operator? 怎么超载这个运算符?

Here's an approach using commas: 这是一种使用逗号的方法:

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

};

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

Some explanations: 一些解释:

The syntax matrix << 5, 10, 15, 20 is achieved in two steps: 语法matrix << 5, 10, 15, 20分两步实现:

  • matrix << 5 is evaluated first; 首先评估matrix << 5 ; it sets the first element to 5 and returns a temporary Adder object that handles further insertions (remembering the index for the next insert) 它将第一个元素设置为5并返回一个临时Adder对象,该对象处理进一步的插入(记住下一个插入的索引)
  • Adder has overloaded operator, that performs the following inserts after each comma. Adder重载operator,在每个逗号后执行以下插入。

An approach like this would work: 像这样的方法可行:

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

Note that I am using a free operator<< function, and do not use commas between the values. 请注意,我使用的是自由operator<< function,并且不要在值之间使用逗号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM