简体   繁体   English

没有类的重载operator- =

[英]Overloading operator-= without a class

Is it possible to overload -= like this without it being a method of a class? 是否可以像这样重载-=而不将其作为类的方法?

vector<int>& operator-=(int a, int b){
    vector<int> v;
    v.push_back(a); v.push_back(b);
    return v
}

I have a line in a homework assignment that looks something like this: 我在作业中有一条线,看起来像这样:

SomeStructure-=1-=2-=3;

What it is supposed to do is remove the elements with the indexes 1, 2 and 3 from the structure(in that order). 应该做的是从结构中删除索引为1、2和3的元素(按此顺序)。

It seems like the option I tried above is not possible (I was thinking of collecting all the indexes in a vector and then removing them from the structure one by one). 似乎我上面尝试过的选项是不可能的(我正在考虑将所有索引收集到一个向量中,然后从结构中一个一个地删除它们)。 Is there some other way to do this? 还有其他方法吗?

The assignment operator is right to left associative. 赋值运算符从右到左关联。

From the C++ Standard 从C ++标准

5.17 Assignment and compound assignment operators [expr.ass] 5.17赋值和复合赋值运算符[expr.ass]

1 The assignment operator (=) and the compound assignment operators all group right-to-left. 1赋值运算符(=)和复合赋值运算符均从右到左分组。

So this expression 所以这个表达

SomeStructure-=1-=2-=3;

is in any case invalid because you may not write 在任何情况下都是无效的,因为您可能不会写

2 -= 3;

And you may not overload operators for built-in types. 而且,您可能不会对内置类型重载运算符。

I advice to write simply a function for example with name erase which will have parameter of type std::initializer_list In this case you could write 我建议写一个简单的函数,例如用名字擦除,其参数类型为std::initializer_list在这种情况下,您可以编写

SomeStructure.erase( { 1, 2, 3 } );

重载运算符时,作为参数传递的至少一种类型必须non primitive type ,这不是您的情况,这就是为什么我们通常inside classes重载运算符inside classes而很少将其作为global functions重载。

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

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