简体   繁体   English

什么C ++字符串擦除返回*这意味着什么?

[英]what does C++ string erase return *this mean?

So the C++ string function 所以C ++字符串函数

string& erase ( size_t pos = 0, size_t n = npos )

returns *this . 返回*this What does that mean? 这意味着什么? Why do I need it to return anything? 为什么我需要它来返回任何东西?

Example

string name = "jimmy";  
name.erase(0,1);

will erase j and become immy , but why do I need it to return anything at all? 将擦除j并成为immy ,但为什么我需要它返回任何东西?

For method chaining . 对于方法链接 For example, after you erase, you can call == on it to check something: 例如,擦除后,您可以在其上调用==来检查某些内容:

string name = "jimmy";
bool b = name.erase(0,1) == "immy";

这只是为了方便,例如你可以链接这样的调用:

name.erase(0,1).erase(3,1);

In your example you don't need it to return anything, because the expression: 在您的示例中,您不需要它返回任何内容,因为表达式:

name.erase(0,1)

is equivalent to: 相当于:

((void)name.erase(0,1), name)

So for example you could write: 例如,您可以写:

while(name.erase(0,1).size()) {
    std::cout << name << '\n';
}

or: 要么:

while((name.erase(0,1), name).size()) {
    std::cout << name << '\n';
}

or: 要么:

while(name.erase(0,1), name.size()) {
    std::cout << name << '\n';
} 

or: 要么:

while(true) {
    name.erase(0,1);
    if (!name.size()) break;
    std::cout << name << '\n';
}

The standard has decided to give you the choice, probably on the basis that it might as well use the return value for something rather than "waste" it. 标准决定给你选择,可能是因为它可能会使用返回值而不是“浪费”它。

Basically, it sometimes saves a little bit of code that repeats a variable name or takes a reference to an intermediate result. 基本上,它有时会保存一些重复变量名称或引用中间结果的代码。

Some people think that functions that modify the object they're called on should not return anything (the idea being to limit the use of functions with side-effects to one per statement). 有些人认为修改他们被调用的对象的函数不应该返回任何东西(这个想法是限制使用带有副作用的函数到每个语句一个)。 In C++ they just have to live with the fact that the designers of the standard library disagree. 在C ++中,他们只需要接受标准库的设计者不同意的事实。

You can do things like this: 你可以做这样的事情:

void process(std::string const &s) {}

process(name.erase(0,1)); //self-explanatory?

std::cout << name.erase(0,1) << std::endl; 

//etc

And things which the other answers has mentioned. 而其他答案提到的事情。

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

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