咱们在C++中两种类型均可以使用,可是std::string是一个类,具体面向对象的优势,而const char*没有。咱们是下面代码初始化std::string对象。html
[html] view plaincopyiphone
std::string name = "tony"; 函数
td::string name = std::string("tony"); 学习
咱们不须要使用指针,也不须要关心内存释放问题,在做用域超出以后std::string对象别释放。咱们能够经过下面的语句把std::string转化为const char*类型。编码
[html] view plaincopyspa
const char* cstring = name.c_str(); .net
咱们可使用std::string指针类型,可是要配合使用new关键字开辟内存空间,而后再也不使用的时候要经过delete释放内存。设计
[html] view plaincopy指针
std::string* name =newstd::string("tony"); code
… …
delete name;
使用std::string指针对象时候,咱们能够经过下面的代码转化为const char*类型。
[html] view plaincopy
const char* cstring = name->c_str();
const char* 和std::string的在Cocos2d-x中还有不少,咱们会在后面的学习中给你们介绍。
cocos2d::__String是Cocos2d-x经过的一个字符串类,它的设计模拟了Objective-C的NSString类,这因为Cocos2d-x源自于Cocos2d-iphone,cocos2d::__String也是基于Unicode双字节编码。
cocos2d::__String的类图以下图所示,
建立它的主要的静态create函数以下:
[html] view plaincopy
static__String * create (const std::string &str)
static__String * createWithFormat (const char *format,...)
使用create函数的实例代码以下:
[html] view plaincopy
__String* name= __String::create("Hi,Tony");
int num=123;
__String* ns = __String::createWithFormat("%d",num);
cocos2d::__String还提供了一些数据类型之间的转换函数。例如:cocos2d::__String转换为const char*类型,这种转换用的比较多的,示例代码以下:
[html] view plaincopy
__String* name= __String::create("Hi,Tony");
const char *cstring=name->getCString();
const char*转换为cocos2d::__String类型,示例代码以下:
[html] view plaincopy
const char* cstring = "Hi,Tony";
__String*ns=__String::createWithFormat("%s",cstring);
std::string转换为cocos2d::__String类型,示例代码以下:
[html] view plaincopy
std::string string = "Hi,Tony";
__String*ns=__String::createWithFormat("%s",string.c_str());
cocos2d::__String转换为int类型,示例代码以下:
[html] view plaincopy
int num = 123;
__String* ns =__String::createWithFormat("%d",num);
int num2 = ns->intValue();
还有不少函数咱们会在之后的学习再给你们介绍。