vc++如何创建程序-构造和继承

#include<iostream.h>
//定义一个动物类
class Animal
{
public:
void eat();//添加方法
{
cout<<"animal eat"<<endl;
}
void sleep();//添加方法
{
cout<<"animal sleep"<<endl;
}
void breathe();//添加方法
{
cout<<"animal breathe"<<endl;
}
};
//定义一个鱼的类

class fish
{
public:
void eat();//添加方法
{

}
void sleep();//添加方法
{

}
void breathe();//添加方法
{

}
};

如果还想定义一个猫,狗,羊......一个一个类的去定义太麻烦了

//用继承的办法来定义一个鱼的类
//那么Animal类有的方法,fish就会继承
class fish :public Animal
{

};

//fish 调用sleep方法
void main()
{
Animal an;
fish fh;
fh.sleep();
}

类的继承,父类(基类),子类(派生类)

有三种继承的方式,public,private (在内部也不能被访问,否则,编译会出错,如下图,把breathe这个方法定义为了私有,那么,在fish中是不能访问来调用这个方法的),protected(对其子类来说,在内部可以访问的)

#include<iostream.h>
//定义一个动物类
class Animal
{
public:
Animal()
{
cout<<"animal construct"<<endl;
}
void eat()//添加方法
{
cout<<"animal eat"<<endl;
}
void sleep()//添加方法
{
cout<<"animal sleep"<<endl;
}
void breathe()//添加方法
{
cout<<"animal breathe"<<endl;
}
};
//用继承的办法来定义一个鱼的类
//那么Animal类有的方法,fish就会继承
class fish :public Animal
{
public:
fish()
{
cout<<"fish construct"<<endl;
}
};

//fish 调用sleep方法
void main()
{
Animal an;
fish fh;
fh.sleep();
}

(在构造过程中是基类先构造)

若定义一个析构函数来调用,是鱼先析构,Animal后析构(析构先子类后父类)

原文地址:https://www.cnblogs.com/fanglijiao/p/9735717.html