#include <string>
#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak() {
cout << "animal speaking" << endl;
}
};
class Cat : public Animal {
public:
void speak() {
cout << "Cat speaking" << endl;
}
};
void test1() {
Animal* animal = new Cat; // 疑惑这里是不是发生了 向上转型
// 和Animal *animal = (Animal *)(new Cat); 一样???
// 向上转型 导致指针步长 变短,会不会有些数据访问不到
// 答 会不会有些数据访问不到? 是的 子类特有的成员,是父类指针是无法访问到的
animal->speak();
}
void test2() {
Animal* animal = (Animal*)(new Cat);
animal->speak();
}
int main()
{
//test1();
test2();
return 0;
}
疑惑:
test1 与 test2 实际上是不是一样的呢?