gpt4 book ai didi

c++ - 在 C++ 中使用多态性访问类的孙子类

转载 作者:太空狗 更新时间:2023-10-29 21:13:23 25 4
gpt4 key购买 nike

我被要求以多态方式实现这个图表,输出是计算几何:

标准如下:

  • print() 和getArea() 函数放在基类Shape 中。还问它是纯虚函数,但我开始怀疑它(..?)
  • getPerimeter()函数放在2d类中,getVolume()函数放在3d类中
  • 维度形状的每个 child 都有getArea()和getPerimeter()或getVolume(),取决于维度,它的功能是计算

这是我所做工作的片段。为了缩短,我将以 2d 类为例:

//base initiation
class Shape{
public:
virtual void print(){};
virtual void getArea(double n){};
};

//2d class which is derived from base class
class TwoDimensionalShape : public Shape{
public:
virtual void getPerimeter(double n){};
};

//The actual shape
class Circle : public TwoDimensionalShape{
protected:
double perimeter, area;
public:
void getArea(double radius){
this->area=(3.1415*radius*radius);
}
void getPerimeter(double radius){
this->perimeter=(3.1415*2*radius);
}
void print(){
cout << "Circle's perimeter: " << this->perimeter << endl;
cout << "Circle's area: " << this->area << endl;
}
Circle(){};
~Circle(){};
};

对于用法本身是:

//setting the object as global
Shape *object;
//the class
void circle(){
Circle circle;
object=&circle;
double radius;
system("cls");
do{
cout << "Enter radius value: ";
cin >> radius; flush();
} while (radius<=0);
object->getPerimeter(radius); object->getArea(radius);
object->print(); cin.get();
}

我觉得我做的不错,但不是!错误列表显示:

Error   4   error C2039: 'getPerimeter' : is not a member of 'Shape'
Error 5 IntelliSense: class "Shape" has no member "getPerimeter"

我正在考虑使用 cast,但我显然没有使用它的经验。

长话短说,如何仅通过使用 Shape *object(此对象也用于球体、立方体、四面体等)访问任何类型的派生类?

附注这不是 What should the TwoDimensionalShape Class contain? 的拷贝因为它问的是完全不同的事情

编辑 1:是的,签名很糟糕,所以我稍后会在我的桌面上编辑我的代码以及这个,所以请继续。谢谢!

最佳答案

how do I able to access any kind of derived class only by using Shape *object

你不能。如果你知道某物是二维形状,你应该通过这样的接口(interface)访问它(不管你是将 &circle 向上转换为二维形状指针还是向下转换 Shape指针,至少在这个特定的例子中)。 Shape 基类没有 getPerimeter 函数,因此不允许您使用它。

关于c++ - 在 C++ 中使用多态性访问类的孙子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44308886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com