常量是固定值,在程序执行期间不会改变。这些固定的值,又叫做字面量。
常量可以是任何的基本数据类型,可分为整型数字、浮点数字、字符、字符串和布尔值。
常量就像是常规的变量,只不过常量的值在定义后不能进行修改。
1.指针应用(1):
#include <iostream>
using namespace std;//指针应用
int main ()
{int a = 20, b = 40;int *p1 = &a ,*P2 = &b;cout <<"a= "<< a <<","<< "b=" <<"b"<<endl;return 0;
}
2.指针应用(2):
#include <iostream>
using namespace std;//指针应用
int main ()
{int a = 30 ,int b = 40;int *p1 = &a ,*p2 = &b;cout <<"a= " << a << endl;cout <<"b= " << b << endl;cout <<"a= " <<(*p1)<<endl;cout <<"b= " <<(*p2)<<endl;return 0;
}
3.指针应用(3)优先级判定
#include <iostream>
using namespace std;//指针应用
int main ()
{int a = 50;int *p = &a;cout << "a= " <<a <<endl;cout << "*p= "<<(*p++) <<endl; //优先级判定return 0;
}
4.指针变量作为函数参数
函数的参数可以是指针类型,它的作用是将一个变量的地址传送到另一个函数中。
指针变量作为函数参数与变量本身做函数参数不同,变量作函数参数传递的是具体值,而指 针函数作函数参数传递的是内存的地址。
5. 指针应用(3):
封装一个交换变量的函数,将地址里面的值进行交换
#include <iostream>
using namespace std;/*封装一个交换变量的函数,将地址里面的值进行交换
*/
void swapfunc(int *p1,int *p2)
{int temp = 11;temp = *p1;*p1 = *p2;*p2 = temp;}//指针应用
int main ()
{int a ,b;int *p1,*p2;p1 =&a;p2 =&b;if(a>b)swapfunc(pa,pb); cout<<"a= "<< a <<",b="<< b <<endl;cout<< *pa <<","<< *pb <<endl;return 0;
}
6.指针引用---数组
对变量定义另外一个名称,这个名称为该变量的引用
<类型> &<引用变量名> = <原变量名>;
其中原变量名必须是一个已定义过的变量。如:
int max;
int &bufmax = max;
max = 5;
bufmax = 10;
bufmax = max+bufmax;
//max与bufmax 同一个地址
bufmax并没有重新在内存中开辟单元,只是引用max的单元。max与bufmax在内存中占有同一个地址,即同一个地址两个名字。
#include <iostream>
using namespace std;//指针应用
int main ()
{//指针数组int a [5] = {11,25,69,30,40};int *pa = a; //将数组的首地址赋给指针变量 pa pa= &a[0]cout <<"\n通过循环输出的数组a元素值: \n";for(i=0;i<5;i++)cout<<*(pa+i)<<",";cout<< endl << endl; cout <<"a[0]= "<< *pa << endl;*pa = 59;cout <<"a[0]= "<< *pa <<endl;cout <<"结果为:"<< *(pa+1) <<endl;return 0;
}
7.字符串常量:
字符串字面值或常量是括在双引号 " " 中的。一个字符串包含类似于字符常量的字符:普通的字符、转义序列和通用的字符。
您可以使用 \ 做分隔符,把一个很长的字符串常量进行分行。
#include<iostream>
#include<string>using namespace std;int main()
{string aa = "this is c++ program";cout << aa <<endl;string bb = "\n this is c++ program2";cout << bb <<endl;return 0;
}
8.定义常量:
在C++中,有两种简单的定义常量的方式
(1)使用 #define 预处理器
(2)使用 const 关键字
(1) #define 预处理器
#include<iostream>
#include<string>
using namespace std;//预处理器定义: #define identifier value 格式:#define 定义的名字 代表值
#define Length 10
#define Width 6
#define Newline '\n'int main()
{//(1)#define 预处理器int area;area = Length * Width; //面积 = 长 * 宽cout << area ;cout <<Newline ;return 0;}
(2) 使用 const 关键字:
//const 格式: const type variable = value;
//使用const前缀声明指定类型的常量 ,意味着不可改
#include<iostream>
#include<string>
using namespace std;int main()
{const int LENGTH = 10;const int WIDTH = 7 ;const char NEWLINE = '\n';int area ;area = LENGTH * WIDTH ;cout << area << endl;cout << NEWLINE;return 0;
}