结构声明:
1、可以生命在main()函数中,紧跟在括号的后面,内部声明只能被该声明所属的函数使用;
2、也可以将声明放到main()的前面,外部声明可被其后面的任何函数使用。
使用赋值运算符(=)将结构赋值给另一同类型的结构
#include <iostream>
struct inflatable
{
charname[20];
floatvolume;
doubleprice;
};
int main()
{
usingnamespace std;
inflatablebouquet=
{
"sunflowers",
0.20,
12.49
};
inflatablechoice;
cout<<"bouquet:"<<bouquet.name<<" for$"<<bouquet.price<<endl;
choice=bouquet;
cout<<"choice:"<<choice.name<<" for$"<<choice.price<<endl;
return0;
}
结构数组:
#include <iostream>
struct inflatable
{
charname[20];
floatvolume;
doubleprice;
};
int main()
{
usingnamespace std;
inflatableguests[2]=
{
{"bambi",0.5,21.99},
{"Bodzilla",2000,565.99}
};
cout<<"Theguests "<<guests[0].name<<" and"<<guests[1].name
<<"\nhavea combined volume of "
<<guests[0].volume+guests[1].volume<<"cubic feet.\n";
return0;
}
初始化结构数组的规则,可以结合初始化数组的规则(用逗号分隔每个元素的值,并将这些值用花括号括起)和初始化结构的规则(用逗号分割每个成员的值,并将这些值用花括号括起)。
inflatable guests[2]=
{"bambi",0.5,21.99},
{"Bodzilla",2000,565.99}
};
共用体:
它能够存储不同的数据类型,但只能同时存储其中的一种类型。也就是说结构可以同时存储int、long和double,共用体只能存储int、long或double。
可节省空间。
指针
是一个变量,存储的是值的地址,而不是值本身
如home是一个变量,则&home是它的地址
#include <iostream>
int main()
{
usingnamespace std;
intdonuts=6;
doublecups=4.5;
cout<<"donutsvalue="<<donuts;
cout<<"and donuts address="<<&donuts<<endl;
cout<<"cupsvalue="<<cups;
cout<<"and cups address="<<&cups<<endl;
return0;
}
输出地址和地址处的值:
#include <iostream>
int main()
{
usingnamespace std;
intupdates=6;
int*p_updates;
p_updates=&updates;
cout<<"Values:updates="<<updates;
cout<<", *p_updates="<<*p_updates<<endl;
cout<<"Address:&updates="<<&updates;
cout<<", p_updates="<<p_updates<<endl;
*p_updates=*p_updates+1;
cout<<"Nowupdates="<<updates<<endl;
return0;
}
为一个数据对象(可以是结构,也可以是基本类型)获得并指定分配内存的通用格式如下:
typeName * point_name = new typeName;
new来分配内存
#include <iostream>
int main()
{
usingnamespace std;
intnights=1001;
int* pt=new int;
*pt=1001;
cout<<"nighysvalue="<<nights<<":location"<<&nights<<endl;
cout<<"int";
cout<<"value="<<*pt<<":location="<<pt<<endl;
double*pd=new double;
*pd=10000001.0;
cout<<"double";
cout<<"value="<<*pd<<":location"<<pd<<endl;
cout<<"locationof pointer pd: "<<&pd<<endl;
cout<<"Sizeof pt="<<sizeof(pt);
cout<<":Size of *pt="<<sizeof(*pt)<<endl;
cout<<"Sizeof pd="<<sizeof(pd);
cout<<":Size of *pd="<<sizeof(*pd)<<endl;
return0;
}