虚继承
一般继承都会导致内存冗余,所以引用了虚继承
a放在最后且两个指针都指向a。
#include<iostream>
using namespace std;
class AA
{
public:
int a;
};
class BB: virtual public AA
{
public:
int b;
};
class CC:virtual public AA
{
public:
int c;
};
class DD:public BB,public CC
{
public:
int d;
};
int main()
{
cout<<sizeof(AA)<<endl; //4字节
cout<<sizeof(BB)<<endl; //8字节 ->12
cout<<sizeof(CC)<<endl; //8字节 ->12
cout<<sizeof(DD)<<endl; //20字节 BB+CC+ d ->24
DD d;
//d.BB::a;
d.a;
system("pause");
return 0;
}
将子类赋值给父类
只有成员多的可以赋值给少的,少的赋值给多的会出错。
#include<iostream>
using namespace std;
class father
{
public:
int a;
};
class son:public father
{
public:
int b;
};
int main()
{
//father fa;
//fa.a=100;
//son s;
//s=fa; //少赋值多不行
//son s2;
//s2.a=50;
//s2.b=500;
//fa=s2; //多赋值少可以
/*son* s=new son;
s->a=100;
s->b=200;
father *pfa=new father;
pfa=s;
cout<<pfa->a<<endl;*/
/*son s;
s.a=100;
s.b=200;
father &fa=s;
*/
system("pause");
return 0;
}
多态
多态有两类 静态多态 重载函数 和动态多态 继承与虚函数 。
要构成多态:1,必须要有继承关系 2,必须有同名虚函数 3,父类指针去调用虚函数。
构造函数不能是虚函数。
#include<iostream>
using namespace std;
class drink
{
public:
virtual void show()
{
cout<<"drink"<<endl;
}
};
class milk:public drink
{
public:
void show(){
cout<<"milk"<<endl;
}
};
class water:public drink
{
public:
void show(){
cout<<"water"<<endl;
}
};
class coffe:public drink
{
public:
void show(){
cout<<"coffe"<<endl;
}
};
//静态多态
//void glass(milk &m)
//{
// m.show();
//}
//void glass(water &w)
//{
// w.show();
//}
//
//void glass(coffe &c)
//{
// c.show();
//}
void glass(drink &d)
{
d.show();
}
// 静态多态 函数重载
// 动态多态 继承和虚函数
//父类加上virtual 子类可加可不加
// 子类中与父类虚函数同名的函数自动变成虚函数
//构造函数不能为虚函数
//构成多态的条件:1,必须要有继承关系 2,必须有同名虚函数 3,父类指针去调用虚函数
int main ()
{
milk m;
water w;
coffe c;
glass(w);
system("pause");
return 0;
}
指针函数
定义指针:要指向的类型 + * + 变量名
判断变量的类型 去掉变量名剩下的就是类型
判断指针指向的类型 去掉变量名再去掉一个*号,剩下的就是指针指向的类型
#include<iostream>
using namespace std;
void AA(int a,char b)
{
cout<<a<<endl;
cout<<b<<endl;
}
int main()
{
void (*pfun)(int,char)=&AA;//函数指针 定义指针:要指向的类型 + * + 变量名
//判断变量的类型 去掉变量名剩下的就是类型
//判断指针指向的类型 去掉变量名再去掉一个*号,剩下的就是指针指向的类型
pfun(10,'c');
system("pause");
return 0;
}
#include<iostream>
using namespace std;
void AA(int a,char b)
{
cout<<a<<endl;
cout<<b<<endl;
}
class person
{
public:
void show(int a)
{
cout<<"person::"<<a<<endl;
}
};
class chinese
{
public:
void show(int a)
{
cout<<"chinese::"<<a<<endl;
}
};
int main()
{
//person ps;
通过对象调用函数指针 用.* 对象的指针调用 用->*
//void (person::*pfun)(int )=&person::show;
//(ps.*pfun)(100);
person *pps =new person;
void (person::*pfun)(int )=(void (person::*)(int ))&chinese::show;
(pps->*pfun)(13);
system("pause");
return 0;
}