源码
// 15Poly_Upcasting.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream.h"
class Pet
{
public:
void Speak(){}
};
class Dog : public Pet
{
public:
void Speak()
{
cout << "WangWang" << endl;
}
};
void Feeding(Pet& p)
{
}
//问题1:对于Feeding函数,可以传递Dog对象作为参数吗?
//问题2: upcasting的定义是?能给我们的reuse带来何种好处?
int main(int argc, char* argv[])
{
printf("Hello World!\n");
return 0;
}
问题1:对于Feeding函数,可以传递Dog对象作为参数吗?
可以。
问题2: upcasting的定义是?能给我们的reuse带来何种好处?
从派生类到基类的转换在继承表中是往上走的,因此叫upcasting,其总是安全的,因为其将一个特定的对象转换为了一个更通用的对象。唯一的变化是其可能失去某些成员,但它至少还是个instrument,因此编译器不用显式的强制转换。