[英]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';
^
substr
是std::string
的“公共成員函數”,為什么不能使用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
才可用。 在您的特定情況下,似乎很明顯你, this
應該是指key
,但是編譯器認為沒有理由。
另外,string.substr()取一個整數,指示開始位置。 string.end()返回一個迭代器,該迭代器將不起作用。 您可能想在這里執行的是調用string.length()。
只需將第一段代碼替換為:
std::cout << "last five characters: " << key.substr(key.length()-5) << '\n';
而且你應該沒事。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.