您的位置:首页 > 编程语言 > C语言/C++

C++ 容易忽略的细节

2009-12-28 21:17 260 查看
1 超出数据类型指定长度的赋值

(1)无符号数据类型

unsigned char ch1= 336;

unsigned char ch2 = -1;

上面两个赋值都超出了unsigned char 类型的范围,大部分的编译器对这种情况是这么处理的:允许赋值,仅仅给出一个警告,但是是经过modulo之后的值。

cout<<ch1<<ch2<<endl; 而这的结果是 ch1 = 336 modulo 256 = 80, ch2 = -1 modulo 256 = 255 。 取余数。

(2) 对于有符号的书来说,要根据具体的编译器来定。

2 浮点型的有效数字

float类型仅提供6位有效数字,double类型至少提供10位有效数字

3 definitions 和declarations(变量的定义和声明)

主要的区别就是定义要分配存储空间,声明不分配存数空间,仅仅谁说明名字是什么,类型是什么而已。看看下面集中定义和声明的方式:

extern int i; // 声明

int i; //定义

extern double pi = 3.14 // 定义

4 变量的作用范围

从声明开始到范围结束,局部变量覆盖全局变量,看下面的代码片段

int i = 100, sum = 0;

for (int i = 0; i != 10; ++i)

sum += i;

std::cout << i << " " << sum << std::endl

输出结果应该是: i= 100     sum = 45

int sum = 0;

for (int i = 0; i != 10; ++i)

sum += i;

std::cout << "Sum from 0 to " << i << " is " << sum << std::endl;

编译出错,因为i没有被定义(cout中的i)

5 const 变量的作用范围

const的变量的作用范围是本文件,即使它被声明成全局变量。要想在其他文件中使用本文件中定义的const变量,看下面代码

// file_1.cc

// defines and initializes a
const
that is accessible to other files

extern const int bufSize = fcn();

// file_2.cc

extern const int bufSize;

// uses
bufSize
from
file_1

//uses
bufSize
defined in
file_1

for (int index = 0; index != bufSize; ++index)

// ...

在声明和定义处都需要加extern关键字

6  vector<string>::const_iterator 和 const  vector<string>::iterator

看下面两个例子,就能明白二者的区别

for (vector<string>::const_iterator iter = text.begin();

iter != text.end(); ++ iter)

*iter = " ";     // error:
*iter
is
const

vector<string>::const_iterator iter 允许自身变化,但不允许修改它下面指向的数据,即指向的内容是常量

vector<int> nums(10);  // nums

is non

const

const vector<int>::iterator cit = nums.begin();

*cit = 1;               // ok:
cit
can change its underlying element

++cit;                  // error: can't change the value of
cit

const vector<int>::iterator cit 允许修改它指向的下面的数据,不允许自身的变化,即本身是个常量

7 typedef string *pstring

const pstring cstr; 解释这个声明的意思?

相信大部分人是这么理解的,typedef string *pstring 是定义了一个指向string 的指针类型,因此const pstring cstr <=> const string * cstr

即 指向一个const string的指针,但是这是错误的。

正确的解释应该是, cstr是一个const指针,指向string类型的字符串
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: