首页 > 代码库 > c++primer学习笔记(2)-Variables(names initialization scope declare)

c++primer学习笔记(2)-Variables(names initialization scope declare)

Initializers:

1.被初始化的变量在create那一瞬间得到值:double price = 109.99, discount = price * 0.6; 这样的定义是合理的。

Three ways of initialization:

1. int units = 0;

2. int units = {0};

3. int units{0};

4. int units(0);

其中第2和第3为list initialization, 该初始化有一个特点:就是该初始化不允许有可能导致损失信息的情况发生(loss of information) 比如:

long double ld = 3.1415926;

int a{ld}, b = {ld};// error: narrowing conversion required

int c(ld), d = ld; // ok : but value will be truncated

上面的初始化中,a和b的定义是错误的。1. double to int 会损失掉小数部分,2. int 可能容纳不下double .

Variable declarations and Definitions:

extern int i; // declares but does not define i

int j; // declares and define j

extern int k = 3; // definition

extern 一般用于declare在其他文件中的变量,用extern的时候要加上变量的类型,并且不能初始化。

Conventions for Variable Names(c++变量命名规范):

1. An identifier  should give some indication of its meaning.

2. Variable names normally are lowercase---index, not Index or INDEX.

3. Like Sales_item, classes we define usually begin with an uppercase letter

4. Identifiers with multiple words should visually distinguish each word, for example, student_loan or studentLoan, not studentloan.

Scope of a Name :

#include <iostream>
// to use a globe variable and also define a local variable with the same name

int reused = 42;     //reused has globe scope
int main()
{
    int unique = 0; //unique has block scope
    // output#1 : uses globe reused; prints 42 0;
    std::cout << reused << " " << unique << std::endl;
    int reused = 0; //new, local object named reused hides global reused
    // output#2: uses local reused; prints 0 0
    std::cout << reused << " " << unique << std::endl;
    // output#3: explicitly requests the global reused; prints 42 0
    std::cout << ::reused << " " << unique << std::endl;    //:: is a scope operator
    
    return 0;
}
以上代码中,在全局和局部都定义了一个reused, 但是不特别指明要用全局::reused的话,使用的是局部

当在block scope里面的outer scope 和 inner scope里面都定义了相同名字时, 在inner scope里面只能使用inner scope里面的那个名字。

c++primer学习笔记(2)-Variables(names initialization scope declare)