简体   繁体   English

C++ 风格和 0 到 size_t(0) 的转换

[英]C++ style and conversion of 0 to size_t(0)

Is using size_t(0) the same as using 0 in the following code?在以下代码中使用size_t(0)是否与使用0相同?

const string foo = "testing";
const size_t pos = foo.find("i");
string name = foo.substr(size_t(0), pos);

That is, when I put only 0 is it converted to size_t(0) ?也就是说,当我只放0 ,它是否转换为size_t(0) If so, is one form preferred over the other?如果是这样,一种形式是否优于另一种形式? My guess is that size_t(0) is the best one to use because it makes the conversion explicit.我的猜测是size_t(0)是最好使用的,因为它使转换变得明确。 On the other hand, perhaps some programmers consider size_t(0) verbose?另一方面,也许有些程序员认为size_t(0)冗长? I'm guessing in practice no one cares either way.我猜在实践中没有人关心任何一种方式。

That is, when I put only 0 is it converted to size_t(0)?也就是说,当我只放 0 时,它是否转换为 size_t(0)?

The conversion is implicit since substr is:转换是隐式的,因为substr是:

basic_string substr( size_type pos = 0,
                     size_type count = npos );

Thus your cast is superfluous.因此,您的演员阵容是多余的。

You are type casting the 0 to the same argument type, its a very good practice but not necessary cause this will be converted implicitly.您正在将 0 类型转换为相同的参数类型,这是一个非常好的做法,但不是必需的,因为这将被隐式转换。

string substr ( size_t pos = 0, size_t n = npos ) const;

Check out this .看看这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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