简体   繁体   中英

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

I tried to compile the following code

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

And the compiler says

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

substr is a "public member function" of std::string , why can't I use this ?

I know I could just reference key again instead of this , but my original code was

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

In the second use of substr , the string does not have a name, so the only way to refer to it would be this . I fixed it with

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

But I am now curious to why this won't work.

this is only available when you are writing code as part of a non-static method of a class. In your particular case, it seems obvious to you that this should refer to key , but the compiler sees no reason for that.

Also, string.substr() takes an integer indicating the beginning position. string.end() returns an iterator, which will not work. What you likely want to do here is call string.length().

Simply replace the first piece of code with:

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

And you should be okay.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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