1.继承
继承表示,子类可以获取父类的属性和方法,然后可以写子类独有的属性和方法,或者修改父类的方法。类可以继承父类的公共成员(public),但不能继承私有成员(private),私有成员只能在父类内部访问。
1.1 案例一单继承
#include <iostream>
using namespace std;
class friut
{
public:
friut()
{
cout << "fruit constructor" << endl;
}
~friut()
{
cout << "fruit destructor" << endl;
}
void show()
{
cout << "fruit show" << endl;
}
};
class Apple: public friut
{
public:
Apple()
{
cout << "Apple constructor" << endl;
}
~Apple()
{
cout << "Apple destructor" << endl;
}
};
int main()
{
Apple apple;
apple.show();
return 0;
}
//fruit constructor
//Apple constructor
//fruit show
//Apple destructor
//fruit destructor
通过上面的代码可以知道,子类apple继承了父类fruit公共属性,子类可以调用show方法。
1.2.1案例二多继承,各个父类成员变量不重名
#include <iostream>
using namespace std;
class base1
{
public:
int a;
base1(int x)
{
a = x;
cout << "base1 constructor" << endl;
}
};
class base2
{
public:
int b;
base2(int y)
{
b = y;
cout << "base2 constructor" << endl;
}
};
class test:public base1, public base2
{
public:
int c;
test(int x, int y, int z):base1(x), base2(y)
{
c = z;
cout << "test constructor" << endl;
}
void show()
{
cout << "a: " << a << ", b: " << b << ", c: " << c << endl;
}
};
int main()
{
test t(1, 2, 3);
t.show();
return 0;
}
//base1 constructor
//base2 constructor
//test constructor
//a: 1, b: 2, c: 3
通过案例可以知道,test继承了base1, base2两个父类,并且拥有了两个父类的属性,这就是多继承。
1.2.3案例三多继承,各个父类成员变量重名
#include <iostream>
using namespace std;
class base1
{
public:
int a;
base1(int x)
{
a = x;
cout << "base1 constructor" << endl;
}
};
class base2
{
public:
int a;
base2(int y)
{
a &