#include <iostream>
#include <cstring>
struct CandyBar
{
char *brand;
double weight;
int calories;
};
void set(CandyBar & cb,char *brand="Millennium Munch",double wegiht=2.85,int calories=350);//设置默认参数
void show(const CandyBar & cb);
using std::cout;
using std::cin;
using std::endl;
int main()
{
CandyBar candybar;
set(candybar);
show(candybar);
delete [] candybar.brand; //由于再次使用时会对candybar.brand指针重新赋值,所以在此前要先释放该内存
set(candybar,"Mario",3.98,300);
show(candybar);
delete [] candybar.brand; //同理,使用完后要释放candybar.brand指向的动态存储空间
return 0;
}
void show(const CandyBar & cb)
{
cout<<"brand: "<<cb.brand<<endl;
cout<<"weight: "<<cb.weight<<endl;
cout<<"calories: "<<cb.calories<<endl;
cout<<endl;
}
void set(CandyBar & cb,char *name,double weight,int calories)
{
cb.brand=new char[strlen(name)+1];
//注意这里不能直接让cb.brand=name,因为cb.brand是一个还没有确定存储位置的空指针,
//直接对其赋值是危险的,编译不会报错,但运行时会出错
//而使用new后则是开辟了一段动态存储空间并让cb.brand指向它,
//此时cb.brand的存储位置才是确定的,才能对它赋值
cb.brand=name; //此时才可以对cb.name指针赋值
cb.weight=weight;
cb.calories=calories;
}
本题的关键在于对char指针的处理
大家可以看看另一篇我转的文章:char *p 与char p[] 比较一些总结