一、概括
在基于对象的程序设计中,我们基于内置数据类型构造我们自己的类类型,而面向对象的编程方式中,我们利用类对象来构建新的类对象,效率将大幅提高。
二、组合方式
最简单的利用方式和基于对象的程序设计一样,采用简单的包含类对象的方式。
#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的指针,父类的虚函数在子类的前面,如果有覆盖则用子类的虚函数替代父类的虚函数。
//虚函数的作用是用一个统一的接口去访问继承树中的子类,以不变应万变。