开始研究C++继承。
先自己写一个试试……
#include <iostream>
using namespace std;
class J
{
public:
void JJ() { cout << "88" << endl; }
};
class S : public J
{
public:
void SS() { cout << "99" << endl; }
};
void main()
{
J mmm;
S nnn;
mmm.JJ();
nnn.JJ();
nnn.SS();
}
公有继承:
当类的继承方式为公有继承时,基类的共有和保护成员的访问属性在派生类中不变。而基类的私有成员不可直接访问。
私有继承:
当类的继承方式为私有继承时,基类中的共有成员和保护成员都以私有成员身份出现在派生类中,而基类的私有成员在派生类中不可直接访问。
保护继承:
保护继承中,基类的公有成员和保护成员都以保护成员的身份出现在派生类中,而基类的私有成员不可以直接访问。
另外,派生类对基类的继承无法继承构造函数与析构函数。于是产生了一些问题。
为此,必须在派生类中另外初始化。
然后是例子:
#include <iostream>
using namespace std;
class S1
{
public:
S1(int i){ cout << "constructing S1" << i << endl; }
};
class S2
{
public:
S2(int i){ cout << "constructing S2" << i << endl; }
};
class S3 : public S1, public S2
{
public:
S3(int a, int b, int c, int d):S1(a), memberS2(d), memberS1(c), S2(b){}
private:
S1 memberS1;
S2 memberS2;
};
int main()
{
S3 obj(1,2,3,4);
}