c++プロパティの1つ---継承
3185 ワード
#include <iostream.h>
class Animal
{
public:
void eat()
{
cout<<"animal eat"<<endl;
}
void sleep()
{
cout<<"animal sleep"<<endl;
}
};
class Fish:public Animal
{
};
void main()
{
Animal an;
Fish fh;
fh.sleep();
}
2.protectedメンバーは、子クラスの内部にのみアクセスでき、直接アクセスできず、親クラス自体にもアクセスできません.
#include <iostream.h>
class Animal
{
public:
void eat()
{
cout<<"animal eat"<<endl;
}
protected:
void sleep()
{
cout<<"animal sleep"<<endl;
}
public:
void breathe()
{
cout<<"animal breathe"<<endl;
}
};
class Fish:public Animal
{
public:
void test()
{
sleep();
}
};
void main()
{
Animal an;
Fish fh;
fh.test();//
fh.sleep();// 。
}
3.継承中のプライベートメンバーはどうしても布団類にアクセスできません!
4.コンストラクション関数.サブクラスオブジェクトを構築する場合は、親のコンストラクション関数を実行してから、サブクラスのコンストラクション関数を実行します.析出の順序は正反対である.
#include <iostream.h>
class Animal
{
public:
Animal(){cout<<"Animal construction!"<<endl;}
void eat()
{
cout<<"animal eat"<<endl;
}
protected:
void sleep()
{
cout<<"animal sleep"<<endl;
}
public:
void breathe()
{
cout<<"animal breathe"<<endl;
}
};
class Fish:public Animal
{
public:
Fish(){cout<<"Fish construction!"<<endl;}
void test()
{
sleep();
}
};
void main()
{
// Animal an;
Fish fh;
fh.test();//
// fh.sleep();// 。
}
5. 。 , , :
#include <iostream.h>
class Animal
{
public:
Animal(int height,int weigtht)//
{cout<<"Animal construction!"<<endl;}
void eat()
{
cout<<"animal eat"<<endl;
}
protected:
void sleep()
{
cout<<"animal sleep"<<endl;
}
public:
void breathe()
{
cout<<"animal breathe"<<endl;
}
};
class Fish:public Animal
{
public:
Fish():Animal(300,400)
{cout<<"Fish construction!"<<endl;}
void test()
{
sleep();
}
};
void main()
{
// Animal an;
Fish fh;
fh.test();//
// fh.sleep();// 。
}