从父类B中继承了两个子类A和C,如果有个类D,想要多继承继承A和C,就会报错,因为在C中生成了两份B的内容,d会不知道访问哪一个。
#include<iostream>
#include <string>
using namespace std;
class B
{
public:
int hhh;
};
class C :public B//在这里和下面加virtual
{
public:
};
class A :public B//在这里和上面加virtual 报错是因为在d1中有两个B的内容,加virtual可以让子类A和C在继承时知道,D想要同时继承我和我的兄弟类(兄弟类就是同时继承自父类B的其他类),那在D中就只生成一份B的内容即可。父类B被称为虚基类
{
public:
};
class D :public A, public C
{
public:
};
void main(void)
{
D d1;
d1.hhh = 100;//此时会报对hhh的访问不明确,因为在d1中有两个B的内容
system("pause");
}
虚基类成员的可见性
1.如果某个属性或方法在A和C中都有定义,D就不知道访问那个了,会报错
2.如果某个属性或方法只在A C其中一个有定义,不管在B中有没有定义,D就会访问A或者C中的(B的优先级低,不会访问D)
3.如果某个属性或方法在B 中有定义,A C中没定义,就访问B 中的
构造函数和虚继承
如果B没有默认构造函数,且B是虚基类,则必须在D中对B 给参数进行初始化。如果D还要派生子类,则在派生的子类中也必须要对B初始化。
如果A C 以非虚继承的方式从B派生出来,则在D中不用对B进行初始化,如果非要初始化就会报错。
#include<iostream>
#include <string>
using namespace std;
class B
{
public:
int hhh;
//B() { cout << "调用了b的无参数的构造函数"<<endl; }
B(int h) { cout << "调用了b的一个参数的构造函数" << endl; }
};
class C : virtual public B
{
public:
int hhh;
C(int h):B(h) { cout << "调用了子类C的构造函数" << endl; }
};
class A :virtual public B
{
public:
int hhh;
A(int a) :B(a){ cout << "调用了A一个参数的构造函数"<<endl; }
};
class D :public A,public C
{
public:
D(int a) : A(a),C(a),B(a) { cout << "调用了D一个参数的构造函数" << endl; }
};
void main(void)
{
D d1(10);
system("pause");
}
虚基函数(c++中多态的实现)
静态多态是程序编译时就根据调用函数所提供的信息,将它所对应的具体函数确定下来,就是在编译时就把具体函数名与具体函数绑定在一起。静态多态主要通过函数重载和运算符重载实现。
动态多态是指在执行函数调用时才能取得对应的信息,确定调用函数所对应的具体函数,即在调用时才调用函数与具体函数绑定在一起。
#include<iostream>
#include <string>//如果直接用子类来定义子类,C c1;那给父类加不加virtual都一样,都是输出“C的hhh“
using namespace std;
class B
{
public:
void hhh();
void hhh2();
};
void B::hhh()
{
cout << "B的hhh";
}
class C :public B
{
public: void hhh() { cout << "c的hhh"; };
};
void main(void)
{
C c1;
c1.hhh();
c1.B::hhh();
system("pause");
}
动态多态(虚基函数)思路
1.我想让一个指针既可以指向他的父类也可以指向他的子类 ,那我只有用父类来定义这个指针
Animal *p1;
当我让他指向父类对象时,他就指向父类。Animal animal1;p1=& animal1;
指向子类对象时,就指向子类。Cat cat1;p1=&cat;
但是有个问题,它指向子类时,如果子类中重写了父类中的某个方法,通过它调用不到重写的方法,只能调用到重写前父类的方法,如图。
为了让指针能访问到重写后的方法,就要在父类的该方法前加上virtual,告诉Animal的指针,以后再指向我儿子的时候,如果我儿子重写了这个方法,就用我儿子的,如果没重写,再用我的。
#include<iostream>
#include<stdlib.h>
using namespace std;
class Animal
{
public:
int name = 01;
virtual void eat() { cout << "动物爱吃什么" << name << endl; }
};
class Cat :public Animal
{
public:
int name = 02;
void eat() { cout << "猫爱吃鱼" << name << endl; }//如果一个方法和父类中它的方法,方法名一致,参数列表一致,且父类的方法是virtual,父类的指针访问的应该是重写后的方法
};
class Dog :public Animal
{
public:
int name = 03;
void eat() { cout << "狗吃骨头" << name << endl; }
};
void print(Animal * animal)//print函数可以调用不同子类中的eat函数
{
animal->eat();
}
void main()
{
Animal *p1;//定义一个父类的指针,父类的指针可以指向子类。
Dog dog1;
Cat cat1;
p1 = &dog1;//让p1指向一个子类
print(p1);
p1 = &cat1;
print(p1);
system("pause");
}