LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 170|回复: 0

指定变量和函数类型

[复制链接]
发表于 2024-1-26 23:36:37 | 显示全部楼层 |阅读模式
C++ 既是强类型语言,也是静态类型语言;每个对象都有一个类型,并且该类型永远不会更改。 在代码中声明变量时,你必须显式指定其类型或使用 auto 关键字指示编译器通过初始值设定项推断类型。 在代码中声明函数时,必须指定其返回值的类型以及每个自变量的类型。 如果函数未返回任何值,则使用返回值类型 void。 例外情况是,当使用允许任意类型自变量的函数模板时。

在你首次声明变量后,稍后无法更改其类型。 但是,你可以将变量的值或函数的返回值复制到其他类型的另一个变量中。 此类操作称作“类型转换”,这些操作有时很必要,但也是造成数据丢失或不正确的潜在原因。

在声明 POD 类型的变量时,强烈建议你将其初始化,也就是为其指定初始值。 在初始化某个变量之前,该变量会有一个“垃圾”值,该值包含之前正好位于该内存位置的位数。 这是需要注意的 C++ 的一个重要方面,尤其是当你使用另一种语言来处理初始化时。 如果声明非 POD 类类型的变量,则构造函数会处理初始化。

下面的示例演示了一些简单变量声明,并分别对它们进行了说明。 该示例还演示了编译器如何使用类型信息允许或禁止对变量进行某些后续操作。

C++

int result = 0;              // Declare and initialize an integer.
double coefficient = 10.8;   // Declare and initialize a floating
                             // point value.
auto name = "Lady G.";       // Declare a variable and let compiler
                             // deduce the type.
auto address;                // error. Compiler cannot deduce a type
                             // without an intializing value.
age = 12;                    // error. Variable declaration must
                             // specify a type or use auto!
result = "Kenny G.";         // error. Can't assign text to an int.
string result = "zero";      // error. Can't redefine a variable with
                             // new type.
int maxValue;                // Not recommended! maxValue contains
                             // garbage bits until it is initialized.

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表