父类与子类
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>
//C++ 通过继承关系 实现了代码的可重用性
class Human //父类 共性
{
public:
void eat(string food)
{
cout << "i am eatting" << food << endl;
}
};
//子类 是在父类的基础上增加新的功能,体现的是个性
class Student :public Human
{
public:
void study(string course)
{
cout << "i am a student,i am learning " << course << endl;
}
};
//父类的public 代表继承方式
//子类的public 代表访问权限
//:后面不写类型的话 默认为private
class Teacher :public Human
{
public:
void tech(string course)
{
cout << "i am teacher,i am teaching " << course << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Student s;
s.study("C++");
s.eat("佛跳墙");
Teacher t;
t.tech("java");
t.eat("咸菜");
return 0;
}
公有继承
公有继承中,子类除了构造器(包括拷贝构造)和析构器,会全盘接收父类。
#include "stdafx.h"
#include <iostream>
using namespace std;
#if 0
公有继承public
没有影响 子类的成员访问方式
影响了父类中的成员在子类的访问方式, 在子类内,还是子对象
father public
pub pub(public)
pro pro(protected)
pri inaccess(不可见)
说明:
1,全盘接收,除了构造器(包括拷贝构造)与析构器。基类有可能会造成派
生类的成员冗余,所以说基类是需设计的。
2,派生类有了自己的个性,使派生类有了意义
#endif
class Father
{
public:
int x;
protected:
int y;
private:
int z;
};
class Son :public Father
{
public:
int pub;
protected:
int pro;
private:
int pri;
};
int _tmain(int argc, _TCHAR* argv[])
{
Son s;
s.pub;
return 0;
}