在C中:
s轴接夜吃巴坏tructstudent
{
intChinese;
intMath;
inttotal;
};
只有成员变量:语文成绩,数学成绩,总成绩;
怀责费科田流其我们可以随意访问这些成员:
struc军目若督庆算日层tstudenta;//定义结构体a
a.Math=100;
a.Chinese=100;
***.tot***l=200;
//写
printf(“%d%d%d”,a.Chinese,a.Math,***.体格评江下tot***l);//读
如果上面不小心写成:
a.Math=90;
a.北故Chinese=100;
***.tot***l=200;
总成绩不等于各科相加,但计算机不会报错。
每改动一次Chinese或Math,都必须写上***.tot***l=a.Chinese
a.Math;
a.Math=100;
a.Chinese=100;
***.tot*假成第亮艺础期列二**l=200;
a.math=帮度夜稳晚从马90;
***.tot***l=a.mat足盟车h
a.Chinese;
//否则total与各科成绩不一致
在C
中:
structstudent
{
public:
student(intthe_Chinese,intthe_M板想她去息两临举身ath):Chinese(the_Chinese),Math(the_Math),total(t谈夜冷达苏庆扬多演he_Chinese
the_Math){}//构造函数,偷懒了
intget_Chinese(){return(Chinese);
};
//最省事的写法
intget_Math(){return(Math);
}
intget_total(){retu问失更著总聚季伟与卷投rn(total);
}
名书快稳都力间定良节聚voidchange_Chinese(in相直孔料使tnew){Chinese=new;
total=Chinese
Math;
return;
}
voidchange_Math(intnew){Math=new;
total=Chinese
Math;
return;
}
//以上全都是成员函数
private:
intChinese;
intMath;
inttotal;
};
比C中多了一些成员函数。
我们可以方便地初始化(当然写结构体时要多写一些):
structstudenta(100,100);
可以调用成员函数:
printf(“%d”,a.get_total());//输出200,total自动计算了
我们不能直接访问三个成员变量(因为在private里):
a.Math=90群赶孩校低杆育为既就;
a.Chinese=100;
***.tot***l=200;
//统统会报错
printf(“%d%d%d”,a.Chinese,a.Math,***.tot***l);//读也不行,要用a.get_Chin者由取妈裂厚收空选ese()等
要设定成员变量的值,必须通过构造函数或其它成员函数(在public里的):
a.change_Math(90);
printf(“%d”,a.get_total());//输出190
这样改变结构体必须通过十才能究我们定好的方式,避免了一些错误更改,而且也方便不少。
内容来自网友回答
函数概念