多态
#include<iostream>
using namespace std;
class Animal {
public:
virtual void speak() {
cout << "animal speak" << endl;
}
virtual ~Animal()=0;
};
Animal:: ~Animal() {
}
class cat :public Animal {
public:
cat(string name) {
m_name = new string(name);
}
void speak() {
cout << "cat speak" << endl;
}
~cat() {
if (m_name!=NULL)
{
cout << "cat 析构" << endl;
delete m_name;
m_name = NULL;
}
}
string* m_name;
};
void dospeak(Animal& animal) {
animal.speak();
}
class AbstractCalculator {
public:
virtual int getresult() {
return 0;
}
int num1;
int num2;
};
class AddCalculator:public AbstractCalculator {
int getresult() {
return num1 + num2;
}
};
class SubCalculator :public AbstractCalculator {
public:
int getresult() {
return num1 - num2;
}
};
void test() {
AbstractCalculator* abc = new AddCalculator;
abc->num1 = 20;
abc->num2 = 30;
cout << abc->num1 << "+" << abc->num2 << "=" << abc->getresult() << endl;
}
int main()
{
cat cat1("tom");
dospeak(cat1);
test();
}