類、對象、構造函數、setget
1、類的介紹:
1.1 類是對象的類型,對象是類的實例
1.2 成員變量:用來區分同一個類的不同對象,可以是各種類型,簡單類型、指針、引用、複合類型、其他類
1.3 靜態成員,描述整個類的特徵;非靜態成員變量,描述不同對象的特徵
1.4 常量成員,必須在創建一個對象的時候,初始化它的常量成員,且不能修改
1.5 成員函數:用來操作一個類的對象的函數;靜態成員函數:屬於整個類的成員函數
1.6 private 私有,把類的數據成員對外隱藏,使之從外部不可見,稱爲信息隱藏;public 公有,外部通過公有成員函數才能訪問私有對象(則把對象的私有數據保護起來了,這種方式就是封裝)
1.7 成員函數中,構造函數用作生成(創建)一個對象,析構函數用於銷燬一個對象,get/set函數用於獲取/修改成員變量的值
2、構造函數:
1.1 聲明對象時,將自動調用構造函數:構造函數必須公有,函數名和類名一樣,沒有返回值,可以接收參數
1.2 默認構造函數:本身無參數、有參數且參數都有默認值兩種情況(不是一定沒有參數,而是調用時可以不傳參)
1.3 一個類可以有多個重載的構造函數,靠不同的參數列表來區分;但是有且只有一個默認構造函數。
1、不帶默認構造參數:
Moren.h
#ifndef __C__No724Class__Moren__
#define __C__No724Class__Moren__
#include <iostream>
using namespace std;
class Moren
{
public:
int num;
char * name;
float score;
void ScoreManage ();
};
#endif
Moren.cpp
#include "Moren.h"
void Moren::ScoreManage()
{
cout << "Num is :" << num << endl;
cout << "Name is :" << name << endl;
cout << "Score is :" << score <<endl;
}
main.cpp
#include "Moren.h"
int main()
{
Moren stu;
stu.num = 1234001;
stu.name = "小明";
stu.score = 90;
stu.ScoreManage();
return 0;
}
2、帶默認構造函數
Moren.h
#ifndef __C__No724Class__Moren__
#define __C__No724Class__Moren__
#include <iostream>
using namespace std;
class Moren
{
public:
Moren();
int num;
char * name;
float score;
void ScoreManage ();
};
#endif
Moren.cpp
#include "Moren.h"
Moren::Moren()
{
num = 1234002;
name = "小剛";
score = 95;
}
void Moren::ScoreManage()
{
cout << "Num is :" << num << endl;
cout << "Name is :" << name << endl;
cout << "Score is :" << score <<endl;
}
main.cpp
#include "Moren.h"
int main()
{
Moren stu;
stu.ScoreManage();
return 0;
}
3、setget
Setget.h
#ifndef __C__No724Class__Setget__
#define __C__No724Class__Setget__
#include <iostream>
using namespace std;
class Setget
{
public:
int num;
char * name;
float score;
void setScore (int a, char * b, float c);
int getNum();
char * getName();
float getScore();
};
#endif
Setget.cpp
#include "Setget.h"
void Setget::setScore (int a, char * b, float c)
{
num = a;
name = b;
score = c;
}
int Setget::getNum()
{
return num;
}
char* Setget::getName()
{
return name;
}
float Setget::getScore()
{
return score;
}
main,cpp
#include "Setget.h"
int main()
{
Setget stu;
stu.setScore(1234003, "小紅", 100);
cout << "Num is :" << stu.getNum() << endl;
cout << "Name is :" << stu.getName() << endl;
cout << "Score is :" << stu.getScore() <<endl;
return 0;
}