1:为什么不将const用于基本类型?
因为,const用于指针,是为了防止指向的原始数据被修改,程序传递基本类型的时候,它将按值传递,以便函数使用副本。这样,原始数据将得到保护。
2:结构体是怎么传递的?
结构体按值传递时,只要传递结构名glitz即可,要传递它的地址,请使用地址运算符&glitz。按值传递将自动保护原始数据,但这是以时间和内存为代价的。按地址传递课节省时间和内存,但不能保护原始数据,除非对函数使用了const限定符。另外,按值传递意味着可以使用常规的结构成员表示法,但传递指针则必须使用简介成员运算符。
结构体按地址传递的标准格式是:
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
void show(const box *pd);
void compete(box *pd);
int main()
{
using namespace std;
box one={"wangkaixiang",2.0,2.0,2.0,4.2};
show(&one);
compete(&one);
show(&one);
cin.get();
return 0;
}
void show(const box *pd)
{
using namespace std;
cout<<"the maker:"<<pd->maker<<endl;
cout<<"the height:"<<pd->height<<endl;
cout<<"the width:"<<pd->width<<endl;
cout<<"the length:"<<pd->length<<endl;
cout<<"the volume:"<<pd->volume<<endl;
}
void compete(box *pd)
{
pd->volume=pd->height*pd->length*pd->width;
}