C++ 中的primitive type/fundamental type/conversion

前两天在面试的时候其中遇到一个小问题:需要比较一个字符串str_value (value = "10") 和unsigned int int_value 10, 当时没细想就随手写了一个str_value == int_value.str(),对面指出unsigned int并不包含str()方法应该是过不了编译。 后来干脆从另一个方便用atoi把c style的字符串转化成int再和int_value比较 (atoi(str_value.c_str()) == int_value。

和java中Interger类都有parse()的方法不同,C++中fundamental type, 比如int, unsinged int, byte, double等类型属于fundamental type, 他们除了可以在操作符(+-*/...)中使用之外并没有自身的方法,因此类型的转化需要靠其他library中的支持。

View Code
int atoi (const char * str); //convert to int in std
long int atol ( const char * str ); // convert to long in std
double atof (const char* str); //conver to double in std

C++的standard library包括C standard library的部分(以.h结尾但已经deprecated)和其他扩展类型,容器和算法等,提供了实现接口和要求,但并没有给出具体实现(很多开源的库实现了C++的standard library)。atoi的方法属于使用了c标准库的函数,所以必须使用c_str()将std::string转化为c style的字符串。

 

posted on 2013-02-15 09:50  梁霄  阅读(394)  评论(0)    收藏  举报

导航