C++学習ノート(30)純虚関数抽象クラス
2131 ワード
, , , 。 。
, , 。 。 , 。 , , , 。
覚えておいてください.
純虚関数のあるクラスは抽象クラスであり、抽象クラスは実例化できない.
純虚関数を継承するサブクラスは純虚関数を実現しなければ抽象クラスでもある.
覚えておいてください.
子クラスがそれぞれこの方法を実現することを望んでいる(幸運の心理があって実現しなくても親クラスの関数を呼び出すことができる)場合に純虚関数を用いる.
#include <iostream>
using namespace std;
//
class Animal
{
public:
Animal(){} //
virtual ~Animal(){} // ,
void play() //
{
eat();
shout();
sleep();
}
// java interface
virtual void eat() =0;
virtual void shout() =0;
virtual void sleep() =0;
};
class Horse:public Animal
{
// , 。
// public virtual
public:
Horse(){cout << " " <<endl; }
~Horse(){cout << " " <<endl;}
virtual void eat() {cout << " " << endl;}
virtual void shout() {cout << " ~" <<endl;}
virtual void sleep() {cout << " " <<endl;}
};
class Tiger:public Animal
{
public:
Tiger(){cout << " "<<endl;}
~Tiger() {cout<< " " <<endl;}
virtual void eat() {cout << " " << endl;}
virtual void shout() {cout << " ~" <<endl;}
virtual void sleep() {cout << " " <<endl;}
};
int main()
{
//
// Animal a; //error: cannot declare variable ‘a’ to be of abstract type ‘Animal’
Animal *p = NULL;
// p = new Animal; //cannot allocate an object of abstract type ‘Animal’
char n;
cout << " h-- t-- " <<endl;
cin >> n;
if(n == 'h')
p = new Horse;
else
p = new Tiger;
p->play();
delete p; // p
}
/*
1
2
3 ,
4
*/