C++继承访问权限:https://www.runoob.com/cplusplus/cpp-inheritance.html
1. 普通类继承
demo
#include <iostream>
using namespace std;
// 基类
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 派生类
class Rectangle : public Shape
{
public:
int getArea()
{
setHeight(-1);
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// 输出对象的面积
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
2. 模板类继承模板类
和普通继承的区别,在于子类使用父类数据和方法时需要加this->
:
#include <iostream>
using namespace std;
// 基类
template <class vertex_t, class value_t>
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 派生类
template <class vertex_t, class value_t>
class Rectangle : public Shape<vertex_t, value_t>
{
public:
int getArea()
{
this->setHeight(-1); // 模板子类使用模板父类函数和变量需要用:this->
return (this->width * this->height);
}
};
int main(void)
{
Rectangle<int, int> Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// 输出对象的面积
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}