一、概括
在基於對象的程序設計中,我們基於內置數據類型構造我們自己的類類型,而面向對象的編程方式中,我們利用類對象來構建新的類對象,效率將大幅提高。
二、組合方式
最簡單的利用方式和基於對象的程序設計一樣,採用簡單的包含類對象的方式。
#include <stdio.h>
#include <stdlib.h>
#define DOOR_CLOSE 0
#define DOOR_OPEN 1
class door
{
public:
door(int state=DOOR_CLOSE){_state=state;}
void open();
void close();
private:
int _state;
};
void door::open(void)
{
if(_state==DOOR_CLOSE){
_state=DOOR_OPEN;
printf("door is opened\n");
}else{
printf("door is already open!\n");
}
}
void door::close(void)
{
if(_state==DOOR_OPEN){
_state=DOOR_CLOSE;
printf("door is closed\n");
}else{
printf("door is already closed!\n");
}
}
class house
{
public:
house(){front_door=door(DOOR_OPEN);}
door front_door;
};
int main(void)
{
house myhouse;
myhouse.front_door.close();
myhouse.front_door.open();
myhouse.front_door.open();
system("pause");
return 0;
}
//內部類對象的初始化將調用內部對象的構造函數。
三、繼承方式
繼承方式提供了更大的靈活性,可以對父對象進行細微的修改。
#include <stdio.h>
#include <stdlib.h>
class person
{
public:
person(const char *name,const char *sex,int age=28,int height=173,int weight=77):_name(name),_sex(sex)
{
_age=age;
_height=height;
_weight=weight;
}
person():_name("justsong"),_sex("male")//c++悲劇的不能調用另一構造函數
{
_age=28;
_height=173;
_weight=77;
}
void info(void)
{
printf("%s :%d,%s,%d,%d\n",_name,_age,_sex,_height,_weight);
}
protected:
const char *_name;
const char *_sex;
int _age;
int _height;
int _weight;
};
class student:public person
{
public:
student():person("cy","female",30,157,65)
{
_grade=6;
}
void info(void)
{
printf("%s :%d,%s,%d,%d,and my grade is %d\n",_name,_age,_sex,_height,_weight,_grade);
}
private:
int _grade;
};
int main(void)
{
person *me=new person();
me->info();
student cy;
cy.info();
system("pause");
return 0;
}
四、在繼承基礎上實現多態
#include <stdio.h>
#include <stdlib.h>
class person
{
public:
virtual void tell(void)
{
printf("I am a person!\n");
}
virtual void eat(void)
{
printf("I eat mantou!");
}
};
class worker:public person
{
public:
void tell(void)
{
printf("I am a worker!\n");
}
void eat(void)
{
printf("I eat mifan");
}
};
class student:public person
{
public:
void tell(void)
{
printf("I am a student!\n");
}
void eat(void)
{
printf("I eat jiaozi!");
}
};
void tell_you(class person* p)
{
p->tell();
}
int main(void)
{
person *me=new person();
tell_you(me);
worker *you=new worker();
tell_you(you);
student *him=new student();
tell_you(him);
printf("%d,%d,%d\n",sizeof(person),sizeof(worker),sizeof(student));
system("pause");
return 0;
}
//對象的最開始處存儲V-TABLE的指針,父類的虛函數在子類的前面,如果有覆蓋則用子類的虛函數替代父類的虛函數。
//虛函數的作用是用一個統一的接口去訪問繼承樹中的子類,以不變應萬變。