C++编程(3)

Educn void void fint pi void pv pi ok pv

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ptnet.edu.cn 指针的运算 假设T* p; p++相当于p变为指向类型为T的下一个元 素的地址,即p和p++之间的实际距离为 sizeof(T) 只有两个指针指向同一个数组的元素时,指 针相减才有意义,结果为两个指针之间数组 元素个数(一个整数) 指针相加没有意义,是不允许的 Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 指针运算示例 void f() { int v1[10]; int v2[10]; int i1 = &v1[5] - &v1[3]; // i1 = 2 int i2 = &v1[5] - &v2[3]; //结果无定义 } int* p1 = v2 + 2; // p1= &v2[2] int* p2 = v2 - 2; // p2无定义 Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 5.4 常量 const是为了描述概念“不变化的值” 常量在编程中非常有用: 许多对象在初始化之后就不再改变自己的 数值 采用符号常量写出的代码更容易维护 指针常常是边读边移动,而不是边写边移 动 许多函数参数是只读不写的 Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 常量示例 const int model = 90; const int v = {1, 2, 3, 4}; const int x; // Error void f() { model = 200; // Error v[2] ++; // Error } void g(const X* p) { //这里不能修改*p } void h() { X val; //val可以被修改 g(&val); // ok //… } 编程中,应系统化地使用符号常量,以避免出现“神秘的数值...
View Full Document

This note was uploaded on 02/10/2014 for the course ECE C++ taught by Professor Xiaoshengtang during the Fall '13 term at BUPT.

Ask a homework question - tutors are online