返回static_cast<int> C++ 和 C

return static_cast<int> C++ and C

本文关键字:gt C++ int lt static cast 返回      更新时间:2023-10-16

我想了解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++工程师的首选。