1,const(具有只读属性,挨谁进限定谁,区分限定变量还是指针)
指向const对象的指针(非const )
const type *cp; 或者type const *cp;//*p的值是常量
指向非const对象的const指针
type* const cp = initAddressValue;//指针的指向固定,不能被修改
const int ival = 5;//ival是定义为常量
const限定的左值引用不可修改
const引用可以绑定到const对象
不能用非const引用指向const对象
const int &r1 = ival;
//正确:引用和所引用的对象都是const int
r1 = 10;
//错误:r1是const的引用,不能修改
int &r2 = ival;
//错误:不能用非const引用指向const对象,可用const引用指向(绑定)非const对象
2,结构体(自定义类型)
struct 结构体类型名{
成员声明;
};
#include<iostream>
#include<string>
using namespace std;
struct d{ //定义结构体d,z
int y,m,day;
};
struct z
{
int number;
string name;
d b; //在结构体z中定义d类型的结构体变量b(结构体的嵌套)
int score;
};
bool cmp(z a,z b){ //型参是z类型
if(a.score<b.score)
return a.score>b.score;}//根据得分降序
int main()
{
z a[100];//定义结构体数组
for(int i=0;i<2;i++)//结构体输入
cin>>a[i].number>>a[i].name>>a[i].b.y>>a[i].b.m>>a[i].b.day>>a[i].score;
sort(a,a+2,cmp);
for(int i=0;i<2;i++)
cout<<a[i].number<<'\t'<<a[i].name<<'\t'<<a[i].b.y<<"年"<<a[i].b.m<<"月"<<a[i].b.day<<"日"<<'\t'<<a[i].score<<endl;//顺序输出并水平制表
}
3,数组与指针
指针可以对数组进行访问:
int a[10];
//指针访问数组元素
for(int *p = a; p < a+10; p++)
cout << *p;
利用bengin(),end()容易写出数组元素的循环程序:
//在数组arr 中查找第一个负数:
int *pb = begin(arr), *pe = end(arr);
while(pb != pe && *pb >= 0)
++pb;
(两个指针相减的结果是它们之间的距离
参与运算的两个指针必须指向同一个数组中的元素)
//逐个输出数组元素的循环
for(auto p = begin(arr); p!= end(arr); ++p)
cout << *p << "\t";
4,string
*赋值注意这种方式:string s4("I am "); string s5(5, 'a'); //s5的内容是aaaaa
*cin输入遇到空格即停,而getline(cin,line)是输入一整行可以读入空格
*字符串可以进行比较
string s1 = "hello";
string s2 = "hello world"; // s2 > s1
string s3 = "Hello"; // s3 < s1, s3 < s2,依据字典顺序比较
*string的链接
string s1 = "hello, ", s2 = "world! " ;
string s6 = s1 + " world" + "\n"; //正确,第一个"+"的结果是string
string s5 = "hello" + "," + s2 ; //错误,不能把字面值直接相加,前两个引号内容不能直接相加
*字符串的处理
string text = "Hello, World!";
for(auto &c : text)//遍历text中的元素
c = toupper(c);
cout << text << endl;