多重基类即之前的多重继承,在利用多重继承生成派生类时,会出现一些问题。
class test1
{
int x;
public:
int getx(){...}
...
};
class test2:public test1
{
};
class test3:public test1
{
};
class test4:public test2,public test3
{
};
test4 x;
int a,b;
a=x.test2::getx();//正确
b=x.test3::getx();//正确
a=x.getx();//错误
为了解决这个问题,我们引入虚拟基类
class test1
{
...
};
class test2:virtual test1
{
};
class test3:virtual test1
{
};
class test4:public test2,public test3
{
};
在基类名前加上virtual
关键字,表示该基类为虚拟基类。以这种方式生成的派生类test4
中,只包含一个test1
的对象。
1、非虚拟基类
/*说明非虚拟基类的用法和作用*/
#include<iostream>
using namespace std;
class test1
{
int x;
public:
test1():x(10)
{
}
int get()
{
return x;
}
void set(int s)
{
x=s;
}
};
class test2:public test1
{
};
class test3:public test1
{
};
class test4:public test3,public test2
{
};
int main()
{
test4 p;
p.test2::set(11);
p.test3::set(12);
cout<<"test2:"<<p.test2::get()<<endl;
cout<<"test3:"<<p.test3::get()<<endl;
}
2、虚拟基类
/*说明虚拟基类的用法合作同*/
#include<iostream>
using namespace std;
class test1
{
int x;
public:
test1():x(10)
{
}
int get()
{
return x;
}
void set(int s)
{
x=s;
}
};
class test2:virtual public test1
{
};
class test3:virtual public test1
{
};
class test4:public test3,public test2
{
};
int main()
{
test4 p;
p.test2::set(11);
p.test3::set(12);
p.set(13);
cout<<"test2:"<<p.test2::get()<<endl;
cout<<"test3:"<<p.test3::get()<<endl;
cout<<"p.get():"<<p.get()<<endl;
}
3、尽管test2
和test3
都是虚拟基类,但是他们的基类是独立存在的。
/*说明虚拟基类的基类是独立存在的*/
#include<iostream>
using namespace std;
class test1
{
int x;int y;
public:
test1():x(0),y(0)
{
}
test1(int a,int b):x(a),y(b)
{
}
void setx(int a)
{
x=a;
}
void sety(int b)
{
y=b;
}
void disp()
{
cout<<"x="<<x<<" "<<"y="<<y<<endl;
}
};
class test2:virtual public test1
{
};
class test3:virtual public test1
{
};
class test4:public test2,public test3
{
};
int main()
{
test4 p;
p.setx(10);p.sety(10);
cout<<"test4:";p.disp();
test2 q=p;
q.setx(20);
test3 r=p;
r.sety(20);
cout<<"test2:";q.disp();
cout<<"test3:";r.disp();
}
由上述程序和运行结果我们可以看出,虽然test2
和test3
都是test4
的虚拟基类,但是test2
和test3
的基类是独立存在的,当我改变其中一个内容时,另一个并不随之改变。