關於物件導向,簡單的來說明,
繼承,就像是父親和兒子的關係
以下面範例~
下面這個範例分為3個部分,分別為
1. class Room
2. class building
3. main()
Room類別 是 父親
building類別 是 兒子
兒子可以使用父親的方法,但是父親不能使用兒子的方法~
class Room{ //分別有 public, protect, private public: Room(){ //建構式: 特殊函示成員,在類別物件建立時執行, //白話講,就是給他預設值啦~ cout<<"Constructor called!!"<x=x; this->y=y; this->z=z; set(x, y, z); } int RoomSize(){ return x*y*z; } void print(){ cout<<"x:"< x=(x>0)?x:1; this->y=(y>0)?y:1; this->z=(z>0)?z:1; } //解構式,程式結束時候呼叫,像是程式結束要存檔! ~Room(){ cout<<"deconstructor called"< set(x*xNew, y*yNew, z*zNew); } //由private改成protected之後,子類別就可以使用x, y, z protected: int x, y, z; };
//building繼承Room類別,也就是building可以用Room類別內所有的方法 class building: public Room{ public: string buildingSize; string buildingName; int buildingNumber; void printBulding(){ cout<<"BuildingSize:"<buildingSize = size; this->buildingName = name; this->buildingNumber = number; Room::set(x, y, z); } };
int main(){ building building1, building2; building1.set(3, 4, 5); building1.setBulding("Large", "GreenBuilding", 001); building2.setBulding("Medium", "RedBuilding", 002); building1.print(); building2.print(); //子物件.父類別::成員; //building1.Room::print(); //building2.Room::print(); return 0; }
沒有留言:
張貼留言