在我的例子中:
在向上转换时,第二个 d.print()
调用不应该打印“base”吗?
它不是“d”派生对象向上转换为基类对象吗?
而在向下转型方面,它有什么优势呢?
你能用实际的方式解释一下向上和向下吗?
#include <iostream>
using namespace std;
class Base {
public:
void print() { cout << "base" << endl; }
};
class Derived :public Base{
public:
void print() { cout << "derived" << endl; }
};
void main()
{
// Upcasting
Base *pBase;
Derived d;
d.print();
pBase = &d;
d.print();
// Downcasting
Derived *pDerived;
Base *b;
pDerived = (Derived*)b;
}
最佳答案
向上转换在 C++ 中是隐式的,在处理虚拟调度时经常使用。换句话说,您有一个指向 Base
的指针,您可以从中访问整个类层次结构的公共(public)接口(interface),并且可以在运行时进行选择。这假设您的接口(interface)函数被标记为 virtual
。示例:
Base* pBase;
cin >> x;
if(x == 0) // this is done at runtime, as we don't know x at compile time
pBase = new Derived1;
else
pBase = new Derived2;
pBase->draw(); // draw is a virtual member function
在这些调度在运行时完成的情况下,它非常有用。简单地说,向上转型允许将派生类视为基类(通过其公共(public)接口(interface))。
向下转换不太有用,IMO 应该尽可能避免。一般来说,这是糟糕设计的标志,因为很少需要将 Base
对象转换为派生对象。可以通过 dynamic_cast
完成(并检查结果) , 喜欢
Base* pBase = new Derived; // OK, the dynamic type of pBase is Derived
Derived* pDerived = dynamic_cast<Derived*>(pBase);
if(pDerived) // always test
{
// success
}
else
{
// fail to down-cast
}
This link提供了一个非常有用的主题介绍。
关于C++——向上转型和向下转型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35102079/