C++ 从CPP中的抽象类继承
我一直在学习CPP继承,我遇到了这个问题:C++ 从CPP中的抽象类继承,c++,inheritance,C++,Inheritance,我一直在学习CPP继承,我遇到了这个问题: Class polygon contains data member width and height and public method set_value() to assign values to width and height. Class Rectangle and Triangle are inherited from polygon class. the classes contain public method calcul
Class polygon contains data member width and height and public method set_value() to assign values to width and height.
Class Rectangle and Triangle are inherited from polygon class.
the classes contain public method calculate_area() to calculate the area of Rectangle and Triangle.
Use base class pointer to access the derived class object and show the area calculated.
我为此问题编写了以下程序:
#include <iostream>
using namespace std;
class Polygon{
float height,width;
public:
void set_value(float height, float width){
this->height=height;
this->width=width;
}
virtual void calculate_area()=0;
};
class Rectangle:public Polygon{
float height,width;
public:
void calculate_area(){
cout << "Area of the rectangle is " << height*width <<endl;
}
};
class Triangle:public Polygon{
float height,width;
public:
void calculate_area(){
cout << "Area of the triangle is " << 0.5*height * width << endl;
}
};
int main(){
Rectangle r1;
r1.set_value(10,20);
Triangle t1;
t1.set_value(10,20);
Polygon *p1;
Polygon *p2;
p1=&r1;
p2=&t1;
p1->calculate_area();
p2->calculate_area();
return 0;
}
#包括
使用名称空间std;
类多边形{
浮动高度、宽度;
公众:
无效集_值(浮动高度、浮动宽度){
这个->高度=高度;
这个->宽度=宽度;
}
虚空计算面积()=0;
};
类矩形:公共多边形{
浮动高度、宽度;
公众:
空隙计算面积(){
在您的代码中,三角形和矩形继承自多边形,因此它们也继承多边形的成员高度和宽度。这些成员在多边形的方法中使用。尽管它们是私有的,因此不能在之外访问多边形
三角形
和矩形
除了从多边形
继承的成员外,还具有成员高度
和宽度
。在三角形
和矩形
的方法中,您正在使用这些成员。它们与从多边形
继承的成员不同。Tria的成员ngle
和矩形
不进行初始化
TL;DR:一种可能的修复方法是通过声明成员受保护
来授予派生类对成员的访问权限,并删除派生类中成员的超级层定义:
#include <iostream>
using namespace std;
class Polygon{
protected:
float height,width;
public:
void set_value(float height, float width){
this->height=height;
this->width=width;
}
virtual void calculate_area()=0;
};
class Rectangle:public Polygon{
public:
void calculate_area() override {
cout << "Area of the rectangle is " << height*width <<endl;
}
};
class Triangle:public Polygon{
public:
void calculate_area() override {
cout << "Area of the triangle is " << 0.5*height * width << endl;
}
};
int main(){
Rectangle r1;
r1.set_value(10,20);
Triangle t1;
t1.set_value(10,20);
Polygon *p1;
Polygon *p2;
p1=&r1;
p2=&t1;
p1->calculate_area();
p2->calculate_area();
return 0;
}
请注意,我在虚拟方法的实现中添加了override
。如果重写正常,则不会产生影响,但如果标记为override
的方法实际上没有重写,则会触发编译器错误(打字很容易发生)类中的宽度和高度是私有的,如何继承它们,我的意思是,私有数据不是永远不会被继承吗?@loveofprogramming否。派生类继承所有基类。private
只是关于可见性和访问性。在您的代码中,Triangle
确实继承了Polygon
的成员ust无法访问它们。如果不是这种情况,则无法从基类继承。当删除其私有类时,类将中断parts@loveofprogramming每个三角形
都有一个完整完整的多边形
子对象。如果移除其成员,则该子对象将没有多大用处提示:使用并避免这->
让你的构造函数一团糟。
Area of the rectangle is 200
Area of the triangle is 100