1、class的构成
class 类名{
public://公有成员
函数1;
变量1;
……
private://私有成员
函数2;
变量2;
……
};
#include <iostream>
using namespace std;class score{
public:
inline void setscore(int m,int f);
inline void showscore();
private:
int mid_exam;//不能在类声明中给数据成员赋值int mid_exam=90;
int fin_exam;
};inline void score::setscore(int m,int f)
{
mid_exam=m;
fin_exam=f;
}inline void score::showscore()
{
cout<<"期中成绩为:"<<mid_exam<<"\n期末成绩为:"<<fin_exam<<"\n总评成绩:"
<<(int)(0.3*mid_exam+0.7*fin_exam)
<<endl;
}int main(int argc, char** argv)
{
score a,*ptr;//
ptr=&a;
a.setscore(90,80);
a.showscore();
ptr->setscore(90,85);
ptr->showscore();
a.showscore();
return 0;
}
2、类的构造函数与析构函数
1>构造函数主要用于为对象分配空间;进行初始化。
注意:名字必须和类名相同,可以有任意类型的参数,但是不能有返回值。
不需要用户调用,而是在建立对象时自动执行。
数据成员一般为私有成员。
参数列表中,是按照他们在类里面被声明的顺序进行初始化的,与他们在成员初始化列表中的顺序无关
#include <iostream>
using namespace std;class score{
public:
score(int m,int f);
inline void showscore();
private:
int mid_exam;
int fin_exam;
};
score::score(int m,int f)
{
cout<<"构造函数使用中…………\n";
mid_exam=m;
fin_exam=f;
}//score::score(int m,int f):mid_exam(m),fin_exam(n)参数列表
//{函数体(可以为空,但必须要有大括号)}
inline void score::showscore()
{
cout<<"期中成绩为:"<<mid_exam<<"\n期末成绩为:"<<fin_exam<<"\n总评成绩:"
<<(int)(0.3*mid_exam+0.7*fin_exam)
<<endl;
}int main(int argc, char** argv)
{
score a(90,85);
a.showscore();
return 0;
}
2>析构函数
撤销对象时的一些清理工作,如释放分配给对象的内存空间。
注意:
析构函数没有返回类型,没有参数,而且不能重载。在一个类中只能有一个析构函数。
当撤销对象时,编译系统会自动的调用析构函数。
对于大多数类而言,默认的析构函数就能满足要求。但是如果有new的话,必须定义析构函数进行delete释放。
3>
使用无参构造函数时,定义 类型名 对象 ()//不要加括号,加括号就声明了一个函数