繁体   English   中英

返回static_cast <int> C ++和C

[英]return static_cast<int> C++ and C

我想了解C和C ++语言。

C ++使用:

return static_cast<int>

如何将return static_cast<int>为C?

例如:

  • C printf()
  • C ++ cout

C样式转换只不过是用括号中的类型为值加上前缀。 代替

static_cast<type>(value)

你只是做

(type)value

例如

static_cast<int>(x)

变成

(int)x

或者你可以做

#ifdef __cplusplus
    #define STATIC_CAST(Type_, Value_) static_cast<Type_>(Value_)
#else
    #define STATIC_CAST(Type_, Value_) (Type_)(Value_)
#endif

并使用两种语言的一次调用

STATIC_CAST(int, x) // C++ static_cast<int>(x), C (int)(x)

简单情况下,不需要在C版本中使用Value_括起来的多余括号,但它们存在,因为这是一个宏,如果您说

STATIC_CAST(int, 1.0 + 2.0)

你不希望它扩展到

(int)1.0 + 2.0

但希望它扩展到

(int)(1.0 + 2.0)

请注意,C ++允许C形式的转换,但是C ++工程师更喜欢模板化转换机制。

暂无
暂无

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

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