派生类强制转换为基类
本文地址: http://blog.csdn.net/caroline_wendy/article/details/24268821
在多态的使用时, 派生类的指针或引用可以转换为基类的指针或引用, 即基类的指针可以指向派生类的基类部分;
Base* b = Derived* d;
b和d指向的内容是相等的, b == d, 因为之间有一个隐式转换即 b == (Base*)d;
b和d的地址是不同的 int(b) != int(d), 因为b指向d的基类部分, d指向的是完整的派生类;
但如果进行隐身转换, int(b) != int((Base*)d), 则地址相同.
代码如下:
/*
* test.cpp
*
* Created on: 2014.04.21
* Author: Spike
*/
/*eclipse cdt, gcc 4.8.1*/
#include <iostream>
class A {
int m_nA;
};
class B {
int m_nB;
};
class C : public A, public B {
int m_nC;
};
int main(void)
{
C* pc = new C;
B* pb = pc;
if (pc == pb) {
std::cout << "equal" << std::endl;
} else {
std::cout << "not equal" << std::endl;
}
if (int(pc) == int(pb)) {
std::cout << "equal" << std::endl;
} else {
std::cout << "not equal" << std::endl;
}
if (int(pc) == int((C*)pb)) {
std::cout << "equal" << std::endl;
} else {
std::cout << "not equal" << std::endl;
}
return 0;
}
输出:
equal
not equal
equal