c++学习记录(六)
c++类继承实践
1.实践预想:子类中调用基类的public、private、protected成员函数
2.代码展示:
#include<iostream>
using namespace std;
class Try
{
public:
Try()
{
cout << "测试友元函数以及构造、析构函数使用" << endl;
length = 0;
height = 0;
weight = 0;
}
~Try()
{
cout << "测试结束" << endl;
}
friend void print(Try try2);
void print2()
{
length += 5;
weight += 3;
height += 6;
cout << "长宽高之积:" << length * height * weight << endl;
}
private:
void print3()
{
length += 5;
weight += 3;
height += 6;
cout << "长宽高之积:" << length * height * weight << endl;
}
protected:
void print4()
{
length += 5;
weight += 3;
height += 6;
cout << "长宽高之积:" << length * height * weight << endl;
}
int length;
int height;
int weight;
};
void print(Try try2)
{
try2.length += 5;
try2.weight += 3;
try2.height += 6;
cout << "长宽高之积:" << try2.length * try2.height * try2.weight << endl;
}
class Stry:public Try
{
public:
int print5()
{
cout<<"长宽高之和:"<<length+weight+height<<endl;
}
};
int main()
{
Stry abc;
}
3.实践理论支撑
(1)派生类可以访问基类中所有的非私有成员
(2)子类不包括基类的构造函数、析构函数和拷贝构造函数
(3)类不包括基类的友元函数
4.实践操作
(1)调用基类友元函数
结论:调用失败,子类不能调用基类友元函数。
(2)调用基类私有变量
结论:子类不能调用基类的私有变量
(3)调用基类私有函数
结论:子类不能调用基类的私有函数
(4)调用基类的保护函数和保护变量
【1】当成员函数为保护类型,成员变量为保护类型时,子类访问成员函数失败
【2】当成员函数为公共类型,成员变量为保护类型时,子类访问成员函数成功