如何声明面积和体积函数

How to declare the area and volume function

本文关键字:函数 何声明 声明      更新时间:2023-10-16
#include <iostream>
using namespace std;
class Shape {
protected:
int _w, _h;
public:
Shape(int w, int h) : _w(w), _h(h) { }
//declaration of area and volume function
};
class Rectangle : public Shape {
public:
Rectangle(int w, int h) : Shape(w, h) { }
};
class Cube : public Shape {
public:
int _b;
public:
Cube(int w, int h, int b) : Shape(w, h), _b(b) { }
int area() { return 2 * (_w * _h + _w * _b + _b * _h); }
int volume() { return _w * _h * _b; }
};
int main() {
Shape *pt;
int w, h, b, v;
cin >> w >> h >> b;
pt = new Rectangle(w, h);
cout << pt->area() << " ";
if ((v = pt->volume()) == -1)
cout << "Undefined ";
else
cout << v << " ";
pt = new Cube(w, h, b);
cout << pt->area() << " ";
if ((v = pt->volume()) == -1)
cout << "Undefined ";
else
cout << v << " ";
}

对于输入4 5 8输出将被20 Undefined 184 160,在另一个测试用例中,输入10 20 10,输出为200 Undefined 1000 2000如何声明和定义 area(( 和 volume(( 以满足给定的测试用例。

欢迎来到 SO。

我相信您正在寻找的是如何为您的两个继承类 Rectangle 和 Cube 声明两个函数。

您可以研究的一般主题称为"多态性",其中父类可以通过其派生类采用多种形式。

下面是您可能倾向于执行但无法按预期工作的示例:

class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
int volume() {
cout << "Parent class volume:" <<endl;
return 0;
}
};

如果您运行上面的代码,会发生什么是父项的区域,而音量函数可能会在定义不明确的情况下运行。这是因为程序将尝试对函数进行静态链接,基本上将它们粘合到位并阻止我们更改它们。

我们希望能够更改面积和体积函数以匹配我们的派生类,因此您需要做的是在父类中将面积和体积函数定义为"虚拟",如下所示:

class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
virtual int volume() {
cout << "Parent class volume:" <<endl;
return 0;
}
};

虚函数将强制派生类(如矩形或立方体(为这些基函数提供自己的函数,方法是告诉程序我们希望让派生类提供函数

如果您将来有疑问,请查看此处的堆栈溢出帖子以获取更多详细信息。他们有很多关于这个主题的答案,如果我在这里错过了什么。

希望这些能帮助你了解如何更好地处理多态性。