【发布时间】:2016-05-08 05:23:31
【问题描述】:
在我的例子中:
在向上转换时,第二个 d.print() 不应该调用 print "base" 吗?
不是将“d”派生对象向上转换为基类对象吗?
而在向下转型时,它有什么优势?
你能用实际的方式解释 upcast 和 downcast 吗?
#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;
}
【问题讨论】:
-
为什么你认为
pBase行应该改变d.print();的行为?你的意思是问pBase->print();吗?
标签: c++ class inheritance downcast upcasting