更新时间:2022-11-23 10:07:34
警告:请勿这样做.您已经被警告了.
WARNING: DO NOT DO THIS. YOU HAVE BEEN WARNED.
您可以使用运算符重载来实现此目的,但这是一个非常糟糕的主意,正如我稍后将解释的那样.
You can achieve this using operator overloading, but it is a very bad idea, as I'll explain later.
我假设类Mat
具有一个采用Mat_<int>
的构造函数.
I'll assume class Mat
has a constructor that takes a Mat_<int>
.
我假设类模板Mat_<T>
具有方法Insert()
,该方法知道如何将单个元素插入矩阵.我会让你解决这个问题,但是它需要一种方法来知道将其插入到哪里.
I'll assume class template Mat_<T>
has a method, Insert()
, that knows how to insert a single element into a matrix. I'll let you work this out, but it'll need a way to know where to insert it.
使用此方法很容易重载operator<<
:
Using this method it is easy to overload operator<<
:
template<typename T>
Mat_<T>& operator<<(Mat_<T>& mat, const T& el)
{
mat.Insert(el);
return mat;
}
我们可以重载operator,
来调用此重载的operator<<
:
And we can overload operator,
to call this overloaded operator<<
:
template<typename T>
Mat_<T>& operator,(Mat_<T>& mat, const T& el)
{
return mat << el;
}
一切正常,您可以使用语法.现在,我将解释为什么这是一个坏主意.
Everything works fine and you can use your syntax. Now I will explain why this is a bad idea.
以这种方式重载operator<<
是完全明智的.这是插入运算符,我们的重载将元素插入矩阵.这是任何人所期望的;到目前为止,一切都很好.
Overloading operator<<
this way is perfectly sensible. This is the insertion operator and our overload inserts an element into the matrix. This is what anybody would expect; so far, so good.
但不是过载operator,
.该运算符的含义是求两个表达式,然后返回最后一个表达式";这显然不是我们的重载运算符所做的.粗心的用户将尝试以标准方式(例如,在for
循环中)使用运算符,
,并且将无法理解为什么他们的代码不起作用.除非您想被使用代码的人所讨厌,否则绝对不要让操作员超负荷执行非标准操作.也许以后你自己.
But overloading operator,
is not. The meaning of this operator is "evaluate two expressions, then return the last one"; this is clearly not what our overloaded operator does. Unwary users will try to use operator ,
in the standard way (for instance, in a for
loop) and will not understand why their code does not work. You should never overload an operator to do a non-standard operation unless you want to be hated by whoever uses your code; probably yourself sometime later.
事实上,尽管标准允许重载operator,
,但是您可能永远不应该这样做,因为不可能编写执行标准操作的代码.您可以认为这是为保持向后兼容性而保留的标准中的错误.
In fact, while the standard allows overloading operator,
, this is something you should probably never do, because it is impossible to write code that does the standard operation. You can consider this a mistake in the standard that is kept for backward compatibility.
并且,如果您考虑重载operator,
以获取两个int
并以某种方式将它们捆绑在一起,则不仅弊端更加严重:当所有操作数都是内置类型时,重载运算符是非法的
And, in case you were considering overloading operator,
to take two int
and somehow bundle them together, not only the drawbacks are even more serious: it is illegal to overload an operator when all operands are built-in types.
因此,总而言之:您可以做到,但这不是一个好主意,并且会在代码的意外位置引起错误.
So, in summary: you can do it, but it is a bad idea and will cause bugs in unexpected places of your code.