简体   繁体   English

operator& 返回一个 int 并对 2 个向量进行操作?

[英]operator& that returns an int and operates on 2 vectors?

I would like to define an & operator between two std::vector<int> .我想在两个std::vector<int>之间定义一个&运算符。 This operator should bit-wise and each element of both vectors together and return the number of non-zero components of the resulting vector.此运算符应按位将两个向量的每个元素放在一起,并返回结果向量的非零分量数。

However, if I define int operator&(const std::vector<int> &lhs, const std::vector<int> &rhs) , it the compiler doesn't like it and requires operator& to return a boolean.但是,如果我定义int operator&(const std::vector<int> &lhs, const std::vector<int> &rhs) ,编译器不喜欢它并要求operator&返回一个布尔值。 Is this actually a restriction with operator& ?这实际上是对operator&的限制吗?

I would like to define an & operator between two std::vector<int> .我想在两个std::vector<int>之间定义一个 & 运算符。

You may not (at least not globally; it can in theory be done in a custom namespace but I recommend against it).你可能不会(至少不是全局的;理论上它可以在自定义命名空间中完成,但我建议不要这样做)。 Operator overloads for standard templates with no user defined type arguments are reserved to the standard library.没有用户定义类型参数的标准模板的运算符重载保留给标准库。

I recommend writing a regular function instead.我建议改为编写常规函数。

Any idea why there's that restriction?知道为什么有这个限制吗?

Because this restriction allows the standard library to change and add any operator overload that the committee wishes without breaking previously well defined programs that have their own conflicting overloads (by virtue of not allowing such overloads to be defined).因为此限制允许标准库更改和添加委员会希望的任何运算符重载,而不会破坏先前定义良好的程序,这些程序具有自己的冲突重载(由于不允许定义此类重载)。


operator& to return a boolean. operator& 返回一个布尔值。 Is this actually a restriction with operator&?这实际上是对 operator& 的限制吗?

No. This is actually not a restriction of binary operator&.不。这实际上不是二元运算符&的限制。 It may return int .它可能会返回int

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

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