!!!Chapter 2 Variable and Basic Types (2.4 ~ 2.9)

2.4 const Qualifier

The const type qualifier transforms an object into a constant. 

When use const to define a variable, it's still an lvalue, but now the lvalue is unmodifiable.

Because we cannot subsequently change the value of an object declared to be const,we must initialize it when it is defined:

const std::string hi = "hello";      //ok: initialized
const int i, j = 0;                  //error: i is uninitialized const

When we define nonconst variable at global scope, it's accessible throughout the program. However, const variables declared at global scope are local to the file in which the object is defined.

We can make a const object accessible throughout the program by specifying that it is extern:

// file_1.cc
// define and initializes a const that is accessible to other files
extern const int bufsize = 1000;
// file_2.cc
extern const int bufsize;                  //declare
//uses bufsize defined in file_1
for (int = 1; int != bufsize; int++)

nonconst variables are extern by default.

2.5 Reference

A reference serves as an alternative name for an object.

A reference is a compound type that is defined by preceding a variable name by the& symbol.A compound type is a type that is defined in terms of another type.

A reference must be initialized using an object of the same type (const or nonconst, int or double...) as the reference.

A reference is just another name for its alias. When a reference is initialized, it remains bound to that object as long as the reference exist. There is no way to rebind a reference to a different object.

int ival = 1024; 
int &refval = ival;       //ok:refval refers to ival
int &refval2;             //error: a reference must be initialized
int &refval3 = 10;        //error: initializer must be an object

A const reference can be initialized to an object of a different type or to an rvalue (The same initializations are not legal for nonconst references)

int = 42;
// legal for const references only
const int &r = 42;
const int &r2= r + i;

A nonconst reference may be attached only to an object of the same type as the reference itself.

A const reference may be bound to an object of a different but related type or to an rvalue.

2.6 Typedef Names

A typedef lets us define a synonym for a type. It can be used as a type specifier. The definition begins with the keywordtypedef, followed by the data type and identifier.
typedef double wages;       //wages is a synonym for double
wages hourly, weekly;       //double hourly, weekly

2.7 Enumerations

Enumerations provide an method of not only defining but also grouping sets of integral constants.
An enumeration is defined using the enum keyword, followed by an optional enumeration name, and a comma-separated list of enumerators enclosed in braces. By default, the first enumerator is assigned the value zero. Each subsequent enumerator is assigned a value one greater than the value of the enumerator that immediately precedes it.
// input is 0, output is 1, test is 2
enum open_modes (input, output, test);
The value used to initialize an enumerator must be a constant expression.
An enumerator value need not to be unique. It is not possible to change the value of an enumerator, as enumerator is itself a constant expression.
// a is 2, b is 3, c is 3, d is 4
enum points (a = 2, b, c = 3, d);
An object of enumeration type may be initialized or assigned only by one of its enumerators or by another object of the same enumeration type:
points t = a;                   //ok: a is a Points enumerator
points s = 3;                   //error: s initialized with int
s = pi;                         //error: pi is not a Points enumerator
s = t;                          //ok: both are objects of Points enum type

2.8 Class Types

In C++ we define our own data types by defining a class.

Each class defines an interface and implementation:

Interface: consists of operations that we expect code that uses the class to execute.

Implementation: includes the data needed by the class. It also includes any functions needed to define the class but that are not intended for general use.

A class definition starts withe the keyword class followed by an identifier that names the class. The body of the class appears inside curly braces. The close curly must be followed by a semicolon.

class Sales_item {
public:
// operations on sales_item objects 
private:
std::string isbn;
unsigned units_sold;
double revenue;
};                                               //must have a semicolon at the end
The operations and data that are part of a class are referred to as its members.The operations are referred to as the member functions and the data as data members.

The class also may contain zero or more publicorprivateaccess label. An access label controls whether a member is accessible outside the class. Code that uses the class may access only the public members. A given label applies until the next access label is seen.

Member functions of the class may use any member of their own class, regardless of the access level.  

We have two keyword to define class:

Class: default access label is private

Struct: default access label is public (like C)

2.9 Writing our own header files

Ordinarily class definitions go into a header file.
To allow programs to be broken up into logical parts, C++ supports what is commonly known as separate compilation
A header provides a centralized location for related declarations.

2.9.1 Designing Our Own Headers

There are two advantages to use header file:
1. All files are guaranteed to use the same declaration for a given entity.
2. When we need to modify declaration, only the header needs to be updated.
Headers are for declaration, not definition.
There are three exceptions to the rule that headers should not contain definitions:classes, const objects whose value is known at compile time, and inline functions.These entities may be defined in more than one source file as long as the definitions in each file are exactly the same.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Why const objects are defined in header
First const variable is local to the file in which it is defined. 
Sometimes, we need constant expression which may contain const (eg. define an enumerator). For const to be a constant expression, the initializer must be visible to the compiler. So we define the const inside a header file. That way the compiler can see the initializer whenever the const is used.
However, there can be only one definition for any variable. Because, by default, const objects are local to the file in which they are defined, it is legal to put their definition in a header file.
Actually, when we define a const in a header file, every source file that includes that header has its own const variable with the same name and value.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

2.9.2 A Brief Introduction to the Preprocessor

The #include facility is a part of C++preprocessor.The preprocessor replaces each #include by the contents of the specified header.
It is common for a header to be included more than once in the same source file.
A common way to make headers safe uses the preprocessor to define a header guard. The guard is used to avoid reprocessing the contents of a header file if the header has already been seen.
The preprocessor lets us define our own variables. To avoid name clashes, preprocessor variables usually are written in all uppercase letters.
The #define directives define and test the state of preprocessor variables.
The #ifndef directives tests whether the specified preprocessor variable has not yet been defined. If it hasn't, then everything following the #ifndef is processed up to the next#endif
We can use #define #ifndef to guard against including a header multiple times:
#ifndef SALE_H
#define SALE_H
// Definition of sale class and related functions goes here
#endif
The #include directive takes one of two forms:
1. #include <stand_header>: it is presumed to be a standard header. The compiler will look for it in a predefined set of locations
2. #include "my_file.h": it is presumed to be a nonsystem header. The search for nonsystem headers usually begins in the directory in which the source file is located.
wiki of #includeguard:http://en.wikipedia.org/wiki/Include_guard
wiki of header file:http://en.wikipedia.org/wiki/Header_file

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值