C++ substr 方法 - "invalid use of ‘this’ in non-member function"

C++ substr method - "invalid use of ‘this’ in non-member function"

我尝试编译了以下代码

std::string key = "DISTRIB_DESCRIPTION=";
std::cout << "last five characters: " << key.substr(this.end()-5) << '\n';

编译器说

error: invalid use of ‘this’ in non-member function
std::cout << "last five characters: " << key.substr(this.end()-5) << '\n';
                                                   ^

substrstd::string 的 "public member function",为什么我不能使用 this

我知道我可以再次引用 key 而不是 this,但我的原始代码是

std::cout << "Description: " << line.substr(found+key.length()+1).substr(this.begin(),this.length()-1) << '\n';

在第二次使用 substr 时,字符串没有名称,因此唯一的引用方式是 this。我用

修复了它
std::cout << "Description: " << line.substr(found+key.length()+1,line.length()-found-key.length()-2) << '\n';

但我现在很好奇为什么 this 不起作用。

this 仅在您编写代码作为 class 的非静态方法的一部分时可用。在您的特定情况下,this 应该引用 key 对您来说似乎很明显,但编译器认为没有理由这样做。

另外,string.substr() 接受一个表示开始位置的整数。 string.end() returns 一个迭代器,这将不起作用。你可能想在这里做的是调用 string.length().

只需将第一段代码替换为:

std::cout << "last five characters: " << key.substr(key.length()-5) << '\n';

你应该没事的。