开发者

what is the operator be overloading here : String8::operator const char*() const

I know it is used to get the containing c string ,similar to std::string.c_str(). But how should I use the operator?

//android/frameworks/base/include/utils/String8.h
458 inline String8::operator const cha开发者_StackOverflowr*() const
459 {  
460     return mString;
461 }  


This is a user-defined conversion, which allows you to convert from a user-defined type to another type.

You could do stuff like this, by using it to get a const char* from a String8 object.

String8 str = "Hello";
const char *cptr = str; // gets const char* from str

std::strlen(str); // std::strlen expects a const char*


It's not so much about how you use it (explicitly), as letting it be used implicitly. Where you'd use .c_str() for a std::string, just leave off the .c_str(). Of course the problem is ambiguity: std::string lacks such an operator for a good reason, and you may occasionally find yourself having to explicitly invoke the operator so the compiler knows which behaviour to use.

EDIT: example in response to UncleBens' comment:

#include <iostream>

struct X
{
    operator const char*() { return "hello world\n"; }
};

int main()
{
    X x;

    std::cout << x.operator const char*();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜