我要创建一个矩阵类,我得到了一些问题,超负荷运营商我怎么能重载<<操作
我想用<<
操作
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;
}
填写一份矩阵
这个操作符如何过载?
我要创建一个矩阵类,我得到了一些问题,超负荷运营商我怎么能重载<<操作
我想用<<
操作
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;
}
填写一份矩阵
这个操作符如何过载?
下面是一个使用逗号的方法:
#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);
}
};
几点说明:
语法matrix << 5, 10, 15, 20
分两步实现:
matrix << 5
先求;它将第一个元素设置为5并返回处理进一步插入的临时对象Adder
已重载operator,
在每个逗号后执行以下插入。像这样的方法是有效的:
#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<<
功能,并且不使用的值之间的逗号。
did you mean:overload – Kos
而在这种情况下,您有两个要重载的运算符:'<<'和','。 – Kos
填写或打印出来? – 2012-11-22 10:57:30