如何声明面积和体积函数
How to declare the area and volume function
#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;
}
};
虚函数将强制派生类(如矩形或立方体(为这些基函数提供自己的函数,方法是告诉程序我们希望让派生类提供函数。
如果您将来有疑问,请查看此处的堆栈溢出帖子以获取更多详细信息。他们有很多关于这个主题的答案,如果我在这里错过了什么。
希望这些能帮助你了解如何更好地处理多态性。
相关文章:
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何在C++函数中声明静态 2D 数组?
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 在函数中声明的 ifStream 对象在发布模式下不起作用
- 函数指针声明
- C++函数的声明和定义不同,但它运行良好
- 当我尝试在函数内声明一个函数时,它不起作用?有什么建议吗?*源代码如下*
- 何时在函数中声明堆栈分配变量?
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 我们可以在main函数中声明嵌套类对象吗
- 在c++中的复制构造函数/一个声明语句中的初始化的延续中使用chain方法
- 在类成员函数中声明类成员变量
- 有没有更优雅的方法在构造函数中声明默认变量?
- 错误 C2512:没有可用的适当默认构造函数:在构造函数中声明带有参数的对象!
- 在函数本身而不是在主函数中声明由参数限定的变量有什么问题?
- 无法理解包装类的构造函数的声明
- 当程序从该函数调谐器时,指向在函数中声明和定义的某些 C 字符串的指针不再有效.为什么?
- 私有使用基构造函数的声明不是私有的
- 模板函数可以使用带有删除的构造函数的声明类型
- C 如何从构造函数中声明(错误C2065未宣布的标识符)