不如就先有一個輪胎類別,小台車要生產就用小輪胎
大台車要大輪胎就生產大的。
範例分為兩部分:
1. Class部分: 產生一個Room的類別
2. main部分: 去使用這個類別
//這邊一開始宣告Room類別 class Room{ //分別有 public, protect, private public: //再來定義他的x, y, z大小 int x; int y; int z; Room(){ //建構式: 特殊函示成員,在類別物件建立時執行, //白話講,就是給他預設值啦~ cout<<"Constructor called!!"<x=x; this->y=y; this->z=z; } int RoomSize(){ return x*y*z; } void print(){ cout<<"x:"<<x <<" ,y:"<<y <<" ,z:"<<z <<" ,size:"<<RoomSize() <<endl; } //記得結尾要分號 };
int main(){ //產生room1 和room2並定義他的x, y, z, //不需要我們自己定義 Room room1(10, 20, 30), room2; room1.print(); cout<<"Room2 Size give you to define!"<>room2.x; cout<<"y:"; cin>>room2.y; cout<<"z:"; cin>>room2.z; room2.print(); if(room1.RoomSize() > room2.RoomSize()){ cout<<"room1 is bigger"<<endl; }else if(room1.RoomSize() == room2.RoomSize()){ cout<<"room1 Size equal to room2 Size"<<endl; }else{ cout<<"room2 is bigger"<<endl; } cout<<"----room[3] Sample----"<<endl; Room room[3]; room[0].x = 20; room[0].y = 30; room[0].z = 40; cout<<"room[0] Size:"<<room[0].RoomSize()<<endl; return 0; }
輸出結果:
沒有留言:
張貼留言