一、多重继承的问题三
实例分析1:多重继承问题3
#include <iostream>
#include <string>
using namespace std;
class BaseA
{
public:
virtual void funcA()
{
cout << "BaseA::funcA()" << endl;
}
};
class BaseB
{
public:
virtual void funcB()
{
cout << "BaseB::funcB()" << endl;
}
};
class Derived : public BaseA, public BaseB
{
};
int main()
{
Derived d;
BaseA* pa = &d;
BaseB* pb = &d;
BaseB* pbe = (BaseB*)pa; // oops!!
BaseB* pbc = dynamic_cast<BaseB*>(pa);
cout << "sizeof(d) = " << sizeof(d) << endl;
cout << "Using pa to call funcA()..." << endl;
pa->funcA();
cout << "Using pb to call funcB()..." << endl;
pb->funcB();
cout << "Using pbe to call funcB()..." << endl;
pbe->funcB();
cout << "Using pbc to call funcB()..." << endl;
pbc->funcB();
cout << endl;
cout << "pa = " << pa << endl;
cout << "pb = " << pb << endl;
cout << "pbe = " << pbe << endl;
cout << "pbc = " << pbc << endl;
return 0;
}
sizeof(d) = 16
Using pa to call funcA()...
BaseA::funcA()
Using pb to call funcB()...
BaseB::funcB()
Using pbe to call funcB()...
BaseA::funcA()
Using pbc to call funcB()...
BaseB::funcB()
pa = 0x6ffdf0
pb = 0x6ffdf8
pbe = 0x6ffdf0
pbc = 0x6ffdf8
BaseB* pbe = (BaseB*)pa; // oops!!
cout << "Using pbe to call funcB()..." << endl;
pbe->funcB();
上述代码按道理应该输出:
Using pbe to call funcB()...
BaseB::funcB()
但实际上输出:
Using pbe to call funcB()...
BaseA::funcA()
原因如下图,
Derived d;
BaseA* pa = &d;指向头部
BaseB* pb = &d;指向脖子
BaseB* pbe = (BaseB*)pa;虽然是BaseB* pbe,但是还是指向头部
通过强制类型转换 BaseB* pbc = dynamic_cast<BaseB*>(pa);可以将pbe指向脖子
实例分析2:正确的多继承方式
#include <iostream>
#include <string>
using namespace std;
class Base
{
protected:
int mi;
public:
Base(int i)
{
mi = i;
}
int getI()
{
return mi;
}
bool equal(Base* obj)
{
return (this == obj);
}
};
class Interface1
{
public:
virtual void add(int i) = 0;
virtual void minus(int i) = 0;
};
class Interface2
{
public:
virtual void multiply(int i) = 0;
virtual void divide(int i) = 0;
};
class Derived : public Base, public Interface1, public Interface2
{
public:
Derived(int i) : Base(i)
{
}
void add(int i)
{
mi += i;
}
void minus(int i)
{
mi -= i;
}
void multiply(int i)
{
mi *= i;
}
void divide(int i)
{
if( i != 0 )
{
mi /= i;
}
}
};
int main()
{
Derived d(100);
Derived* p = &d;
Interface1* pInt1 = &d;
Interface2* pInt2 = &d;
cout << "p->getI() = " << p->getI() << endl; // 100
pInt1->add(10);
pInt2->divide(11);
pInt1->minus(5);
pInt2->multiply(8);
cout << "p->getI() = " << p->getI() << endl; // 40
cout << endl;
cout << "pInt1 == p : " << p->equal(dynamic_cast<Base*>(pInt1)) << endl;
cout << "pInt2 == p : " << p->equal(dynamic_cast<Base*>(pInt2)) << endl;
return 0;
}
p->getI() = 100
p->getI() = 40
pInt1 == p : 1
pInt2 == p : 1
- 一些有用的工程建议
- (1)先继承自一个父类,然后实现多个接口
- (2)父类中提供equal()成员函数
- (3)equal()成员函数用于判断指针是否指向当前对象
- (4)与多重继承相关的强制类型转换用dynamic_cast完成。