C++ 运算符重载 (v << 1,2,3;)?
c++ operator overloading (v << 1,2,3;)?
看看下面的语法:
Matrix<int , 3 , 3 > m;
m << 1, 2, 3,
4, 5, 6,
7, 8, 9;
std::cout << m;
输出:1 2 3
4 5 6
7 8 9
如何重载第一个<<
以下内容可能对您有所帮助:https://ideone.com/Ap6WWt
template <typename T, int W, int H>
class MatrixStream
{
public:
MatrixStream(Matrix<T, W, H>& mat, const T& value) : mat(mat), index(0)
{
*this, value;
}
MatrixStream& operator , (const T& value);
private:
Matrix<T, W, H>& mat;
int index;
};
template <typename T, int W, int H>
class Matrix
{
public:
MatrixStream<T, W, H> operator << (const T& value) {
return MatrixStream<T, W, H>(*this, value);
}
T m[W][H];
};
template <typename T, int W, int H>
MatrixStream<T, W, H>& MatrixStream<T, W, H>::operator , (const T& value)
{
assert(index < W * H);
int w = index / H;
int h = index % H;
mat.m[w][h] = value;
++index;
return *this;
}
但是重载operator ,
是非常不鼓励的。正如评论中所说,您可以使用替代m << {1, 2, 3, 4, 5, 6, 7, 8, 9}
或m << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9
。
当您使用如下表达式时:
CleanInitArray a(6);
a = 1,2,3,4,5,6;
由编译器这样读取:
((((((a=1),2),3),4),5),6);
因此,您需要重载赋值操作符以返回一个类数组对象,并使用该操作符重载逗号操作符。
在我的整个c++生涯中,我所见过的重载operator,
的唯一有用的应用是Boost。赋值,甚至这在c++ 11中也变得多余了,多亏了std::initializer_list
。
尽管如此,知道它是如何工作的也无妨,所以我建议您只查看Boost源代码。它是开源的,您可以免费下载,并且它可以按预期工作。
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多