继承:
首先从一段代码开始:
#include <iostream>
using namespace std;
//动物
class animal{
public:
void eat(){
cout<<"eat"<<endl;
}
void sleep(){
cout << "sleep" << endl;
}
void breath(){
cout << "breat" << endl;
}
};
//鱼
class fish{
public:
void eat(){
cout<<"eat"<<endl;
}
void sleep(){
cout << "sleep" << endl;
}
void breath(){
cout << "breat" << endl;
}
};
//牛
class cot{
public:
void eat(){
cout<<"eat"<<endl;
}
void sleep(){
cout << "sleep" << endl;
}
void breath(){
cout << "breat" << endl;
}
};
//如我我想要个鸡呢???再重写一遍代码吗????
如我我想要个鸡呢???再重写一遍代码吗????,我是个懒人,也是个聪明人,才不会一遍又一遍去做无聊的事情。
用继承,用继承的目的是为了重用代码,说白了就是想少写点代码。那让我们看看用继承如何实现功能?
#include <iostream>
using namespace std;
class animal{
public:
void eat(){
cout<<"eat"<<endl;
}
void sleep(){
cout << "sleep" << endl;
}
void breath(){
cout << "breat" << endl;
}
};
class fish:public animal {
};
class duck:public animal{
};
int main() {
}
加餐:
#include <iostream>
using namespace std;
class animal{
public:
animal(){
cout<<"我是动物"<<endl;
}
void eat(){
cout<<"eat"<<endl;
}
void sleep(){
cout << "sleep" << endl;
}
void breath(){
cout << "breat" << endl;
}
};
class fish:public animal {
public:
fish(){
cout << "我是鱼" << endl;
}
};
int main() {
fish fi;
}
请问控制台会输出什么?animal和fish构造函数的调用顺序是什么??
解释:没有父亲就没有孩子,因为fish是从annimal继承过来的,所以在fish类的对象构造之前,annimal对象要先构造。再多说一点,构造函数和析构函数调用顺序刚好相反。
子类调用父类的构造函数
C++调用父类的构造函数就是在子类构造函数后加上:父类构造函数,这样子类构造函数被调用时,系统就会去调用父类的呆参构造函数。
#include <iostream>
using namespace std;
class animal{
private:
int height;
int weight;
public:
animal(int height,int weight){
this->height = height;
this->weight = weight;
cout<<"我是动物"<<endl;
}
void eat(){
cout<<"eat"<<endl;
}
void sleep(){
cout << "sleep" << endl;
}
void breath(){
cout << "breat" << endl;
}
void output(){
cout << weight << endl << height << endl;
};
};
class fish:public animal {
public:
fish():animal(500,600){
cout << "我是鱼" << endl;
}
};
int main() {
fish fi;
fi.output();
}
多重继承,我不习惯用,所以不到万不得已不用多重继承。