您的位置:首页 > 其它

继承

2016-04-04 14:29 323 查看
//继承
//1.不带参数
#include<iostream.h>
class animal
{
public:
void eat()
{
cout << "animal eat" <<endl;
}
protected:
void sleep()
{
cout <<"animal sleep"<<endl;
}
private:
void breathe()
{
cout<<"animal breathe"<<endl;
}
};

class fish :public animal
//animal 父类 fish 子类
//类中的protected在子类中可以访问,在外部不能
//类中的private在子类都不能被访问
//继承方式:public,private,
{
void test()
{
sleep();
breathe();
}
};

int main()
{
animal an;
an.eat();
fish fh;
fh.sleep();
return 0;
}




//2.带参数

include

using namespace std;

class animal

{

public:

animal(int hight, int weight) //构造函数一般与类的名字相同

{

cout << “animal construct” << endl;

}

~animal()

{

cout << “animal deconstruct” << endl;

}

void eat()

{

cout << “animal eat” << endl;

}

void sleep()

{

cout << “animal sleep” << endl;

}

void breathe()

{

cout << “animal breathe” << endl;

}

};

//fish 继承animal后,其中的构造函数会不会被调用

//结果:fish 继承父类 ,可以调用父类的方法,因此先调用animal中的构造函数,在调用fish中的构造函数

//构造时,父类先,子类后

//析构时,子类先,父类后

class fish :public animal

{

public:

fish() : animal(400, 300),a(1)

//当父类中的构造函数带有参数时,

//当我们构造fish类的对象fh时,

//它需要先构造animal类的对象,

//调用animal类的默认构造函数(即不带参数的构造函数),

//而在我们的程序中,animal类只有一个带参数的构造函数,

//在编译时,因找不到animal类的默认构造函数而出错。

//解决方法:

//fish() : animal(400,300),向父类传递参数,还可以进行常量的初始化

{

cout << “fish construct” << endl;

}

~fish()

{

cout << “fish deconstruct” << endl;

}

private:

const int a;

};

int main()

{

// animal an;

// an.eat();

fish fh;

// fh.sleep();

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  继承 class