1.定义
继承允许我们依据另一个类来定义一个类,这使得创建和维护一个应用程序变得更容易,也达到了重用代码功能和提高执行效率的效果。这个已有的类称为基类,新建的类称为派生类。
class GetVolume :public Box // 引用基类
GetVolume(int a, int b, int c) :Box(a, b, c) {} //对box的构造函数赋值,必须是a和a一致
#include<iostream>
using namespace std;
class Box
{
public:
int Lenght{ 1 };
int width{ 1 };
int height{ 1 };
Box(int x, int y, int z) :Lenght{ x }, width{ y }, height{ z } {}//构造函数
};
class GetVolume :public Box
{
public:
GetVolume(int a, int b, int c) :Box(a, b, c) {} //对box的构造函数赋值,必须是a和a一致
int volume(void)
{
return Lenght * width * height;
}
};
int main()
{
GetVolume Vbox1{ 5,5,5 };
cout << Vbox1.volume() << endl;//结果125
return 0;
}