c++基礎2——類和物件
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>
使用無參建構函式時,定義 型別名 物件 ()//不要加括號,加括號就聲明瞭一個函式