類別介紹
類別為struct的延伸, 裏面的變數稱為屬性, 並在類別裏加了方法及事件. 要建立一個物件, 就需先有類別, 再由類別 new 出一個物件
類別的建立
class 類別名稱{ 
    private: 
        資料型別 成員; 
    public: 
        資料型別 成員; 
    protected: 
        資料型別 成員; 
}
class Car{
    private:
        int void turbo(){
        speed*=2;
    }
    int setSpeed(int s){
        if(s>=0)speed=s;
    }
    int getSpeed(){
        return speed;
    }
};
int main(){
    Car car;
    car.setSpeed(100);
    car.turbo();
    printf("Car speed : %d\n", car.getSpeed());
    car.speed=10;//speed為private, 不能由類別外部取用
    system("pause");
    return 0;
}
類別外定義方法
將方法寫於類別外部,有其特定需求,此時需在類別內部定義原型, 此寫法通常是把class定義於標題檔中,然後方法程式寫於cpp中
class Car{
    private:
        int speed;
    public:
        void turbo();
        int setSpeed(int s);
        int getSpeed();
};
void Car::turbo(){
    speed*=2;
}
int Car::setSpeed(int s) {
    if (s>=0)speed=s;
}
int Car::getSpeed(){
    return speed;
}
int main(){
    Car car;
    car.setSpeed(100);
    car.turbo();
    printf("Car speed : %d\n", car.getSpeed());
    system("pause");
    return 0;
}
建立一個物件 : new
car *car=new Car();
car->setSpeed(100);
car->turbo();
由new建立的動態物件,需使用 ->存取屬性方法
純C語言的寫法
如上的Car, 在純 C 語言如何撰寫呢?? 如下
Car *car=(Car *)malloc(sizeof(Car));
因為 malloc傳回的值為 (void *) 的記憶体位址, 所以要強制轉型為 (Car *)
public
設定為public後,產生的物件就可以直接控制任意變更。為了安全性,通常會把屬性設為private, 再由public 方法進行存取控制,一般會新增getXxx(), getXxx()
方法重載 : 同函數重載
private 破解方法
#include <iostream>
using namespace std;
class Pokemon{
	private:
		int level;
	public:
		void setLevel(int l){
			this->level=l;
		}
		int getLevel(){
			return level;
		}
};
int main(){
	Pokemon *p=new Pokemon();
	p->setLevel(10);
	printf("p->getLevel() : %d\n", p->getLevel());
	//printf("p->level : %d\n", p->level); //error, level被private 封裝了 
	int *l=(int *)p;
	printf("p->level : %d\n", *l);//破解了 
}
			