c++多继承机制
2012-07-23 20:22
127 查看
由于两义性问题的根源在公共基类,因此需要从公共基类着手,将公共基类说明为虚基类,就可以避免二义性。代码如下:
#include<iostream>
using namespace std;
class human
{
public:
void speak(){cout<<"人类可以说话"<<endl;}
};
class father : virtual public human
{
public:
void stand(){cout<<"父亲可以站立"<<endl;}
};
class mother : virtual public human
{
public:
void clean(){cout<<"母亲可以洗衣服"<<endl;}
};
class son : public father ,public mother
{
public:
void school(){cout<<"孩子还在上学"<<endl;}
};
int main()
{
son Tom;
Tom.stand();
father *fp = NULL;
fp = new son;
fp->speak();
//fp->school();
/*son *Fs = NULL;
Fs = new father;*/
/*用基类指针指向一个派生类对象时,由于派生类对象也是基类的对象,因此这种指向是安全的,但只能访问基类所
拥有的成员*/
return 0;
}
![](http://my.csdn.net/uploads/201207/23/1343046187_9428.jpg)
注意:一、father 和mother在继承时将human说明为虚基类,也就是只为子类son生成一个speak函数,speak函数是惟一的,避免了二义性。
二、派生类指针不能直接指向基类对象。
三、派生类指针必须强制转换成基类指针后才可指向基类。
谢谢大家!祝大家心情愉快。
PS:我的第一篇博文。
#include<iostream>
using namespace std;
class human
{
public:
void speak(){cout<<"人类可以说话"<<endl;}
};
class father : virtual public human
{
public:
void stand(){cout<<"父亲可以站立"<<endl;}
};
class mother : virtual public human
{
public:
void clean(){cout<<"母亲可以洗衣服"<<endl;}
};
class son : public father ,public mother
{
public:
void school(){cout<<"孩子还在上学"<<endl;}
};
int main()
{
son Tom;
Tom.stand();
father *fp = NULL;
fp = new son;
fp->speak();
//fp->school();
/*son *Fs = NULL;
Fs = new father;*/
/*用基类指针指向一个派生类对象时,由于派生类对象也是基类的对象,因此这种指向是安全的,但只能访问基类所
拥有的成员*/
return 0;
}
![](http://my.csdn.net/uploads/201207/23/1343046187_9428.jpg)
注意:一、father 和mother在继承时将human说明为虚基类,也就是只为子类son生成一个speak函数,speak函数是惟一的,避免了二义性。
二、派生类指针不能直接指向基类对象。
三、派生类指针必须强制转换成基类指针后才可指向基类。
谢谢大家!祝大家心情愉快。
PS:我的第一篇博文。
相关文章推荐
- 浅谈C++之继承机制
- 深入理解C++面向对象机制(一)多继承
- C++的虚拟继承机制
- 从c++的菱形继承到 C#的接口机制
- 深入理解C++面向对象机制(二)虚继承
- C++对象模型Data语意学分析、虚继承底层实现机制
- C++继承,多态性机制,自学随笔6月11日
- c++ 继承机制易犯的错误
- c++ 继承机制易犯的错误
- C++继承机制的例子
- c++虚函数实现机制以及类继承中的内存分布
- C++的三种继承机制以及继承机制对三种访问权限(public, protected, private)的影响
- 继承机制中的构造器和析构器 - C++快速入门17
- C++中的虚拟继承机制探讨
- 继承机制中的构造器和析构器 - C++快速入门17
- C++学习之路——继承机制
- C++ 和C# 继承机制的差异之浅见
- c++三种继承机制和访问权限
- C++ 继承成员访问控制机制
- C++继承机制