继承语法
继承允许我们依据另一个类来定义一个新的类,这样做达到了重用代码,和提高执行效率的效果。当创建一个类时,不需要重新编写新的成员变量和成员函数,只需指定新建的类继承了一个已有的类即可。这个已有的类称之为基类(父类),新建的类称之为派生类(子类)。
#include<iostream>
using namespace std;
class father
{
private:
int pri;
protected:
int pro;
public:
int pub;
void fun() { cout << "fun()" << endl; }
void eat() { cout << "eat()" << endl; }
};
class son :public father
{
void work()
{
//pri = 1; //父类私有成员不能在子类中访问
pro = 1; //父类受保护的成员可以在子类中访问
pub = 1; //父类公有成员可以在子类中访问
}
};
int main()
{
son s;
s.pub;
s.fun();
s.eat();
return 0;
}
继承方式
- 凡是基类中私有的,派生类都不可以访问。
- 基类中除了私有的成员,其他成员在派生类中的访问属性总是以安全性高的方式呈现。(安全性级别:私有>保护>公有)
private
#include<iostream>
using namespace std;
class father
{
private:
int pri;
protected:
int pro;
public:
int pub;
};
class son :private father
{
void fun()
{
// pri = 1; //父类私有成员不能在子类中访问
pro = 1; //pro可以在son中被访问,但是访问属性是private
pub = 1; //pub可以在son中被访问,但是访问属性是private
}
};
class grandson :public son
{
void fun()
{
// pro = 1; //son中pro的访问属性被改为private,所以不能在grandson中访问
// pub = 1; //son中pub的访问属性被改为private,所以不能在grandson中访问
}
};
int main()
{
son s;
// s.pub = 1; //私有成员不能被访问
return 0;
}
protected
#include<iostream>
using namespace std;
class father
{
private:
int pri;
protected:
int pro;
public:
int pub;
};
class son :protected father
{
void fun()
{
// pri = 1; //父类私有成员不能在子类中访问
pro = 1; //pro可以在son中被访问,但是访问属性是protected
pub = 1; //pub可以在son中被访问,但是访问属性是protected
}
};
class grandson :public son
{
void fun()
{
pro = 1;
pub = 1; //pub在son中是受保护的
}
};
int main()
{
son s;
// s.pub; //pub在father中是公有成员变量,但是以protected方式继承,会缩小访问权限,变成受保护的
return 0;
}
public
#include<iostream>
using namespace std;
class father
{
private:
int pri; //类内访问
protected:
int pro; //类内子类访问
public:
int pub; //类内子类对象访问
};
class son :public father
{
void fun()
{
// pri = 1; //父类私有成员不能在子类中访问
pro = 1; //protected
pub = 1; //public
}
};
class grandson :public son
{
void fun()
{
pro = 1;
pub = 1;
}
};
int main()
{
son s;
s.pub = 1;
// s.pro = 1; //保护成员对象不能访问
return 0;
}
多继承
一个类可以继承多个父类,他可以从多个基类继承变量和函数。定义一个派生类,我们使用一个类派生列表来指定有哪些基类。
#include<iostream>
using namespace std;
class father
{
public:
int pub;
};
class mother
{
public:
int pub;
};
class son :public father, public mother {};
//二义性问题用作用域解决
int main()
{
son s;
s.father::pub = 1;
s.mother::pub = 2;
cout << s.father::pub << ' ' << s.mother::pub << endl;
return 0;
}