继承和多态是C++的特性,它C语言没有这个特性。
C++的三大特性:继承,多态,封装。
继承:分为公有(public)继承,私有(private)继承,保护(protected)继承。
用struct来模拟实现,因为struct在C和C++中都能可以使用,在C中称为结构体在C++中称为类,但他们的原理是一样的,又因为struct的限定符默认是公有的,在C中没有限定符这个概念,所以用c语言只能实现成公有继承
#include<iostream>
#include<stdio.h>
using namespace std;
//
//实现继承
typedef void(*ss)();
struct A
{
ss s;
int a;
};
//struct B
//{
// struct A _a ;
// int b;
//};
//void fun()
//{
// printf("father is ss");
//}
//int main()
//{
// struct A _a;
// struct B _b;
// _b._a.a=1;
// _b._a.s=fun;
// _b.b=2;
// printf("child->father:%d",_b._a.a);
// _b._a.s();
// system("pause");
// return 0;
//}
//实现多态
typedef void(*SS)();
struct A
{
SS s;
int d;
};
struct B
{
struct A _a;
};
void printfc()
{
printf("father....\n");
}
void printfd()
{
printf("child...\n");
}
int main()
{
struct A a;
struct B b;
struct A* a1;
b._a.d=1;
a.s=printfc;
b._a.s=printfd;
a1=&a;
a1->s();
a1=(struct A *)&b;
a1->s();
system("pause");
}