#include<iostream>
using namespace std;
class Mammal
{
public:
virtual void speak()
{
cout << "ohohoh~~~~" << endl;
}
};
class Dog:public Mammal
{
public:
void speak()
{
cout << "woof woof~~~" << endl;
}
};
int main()
{
Dog d;
d.speak();
return 0;
}
//输出:
//woof woof~~~
#include<iostream>
using namespace std;
class Mammal
{
public:
Mammal() { cout << "基类构造函数" << endl; }
virtual ~Mammal() { cout << "基类析构函数" << endl; }
virtual void speak()
{
cout << "ohohoh~~~~" << endl;
}
};
class Dog:public Mammal
{
public:
Dog() { cout << "派生类构造函数" << endl; }
~Dog() { cout << "派生类析构函数" << endl; }
void speak()
{
cout << "woof woof~~~" << endl;
}
};
int main()
{
Dog d;
d.speak();
cout << endl;
cout << "基类指针指向派生类对象" << endl;
Mammal* pDog = new Dog;
pDog->speak();
cout << endl;
pDog->Mammal::speak();
delete pDog;
//无论指针指向的动态类型是什么,最终被调用的总是基类的speak函数
return 0;
}
//输出:
//woof woof~~~