c++ 快速构建一个类计算正方形面积

#include<iostream>
using namespace std;

//创建一个类计算矩形的面积
class space
{
public:
//定义属性
	int r;
	//定义行为
	int cal()
	{
		return r * r;
	}
};

int main()
{
	space c;
	c.r = 10;
	cout <<"面积是"<< c.cal() << endl;
	return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是用 C++ 设计一个抽象计算面积的示例代码: ```c++ #include <iostream> using namespace std; // 抽象 Shape class Shape { public: // 纯虚函数,计算面积 virtual float calcArea() = 0; }; // 派生 Rectangle class Rectangle: public Shape { private: float width; float height; public: Rectangle(float w, float h) { width = w; height = h; } // 实现 Shape 中的纯虚函数 float calcArea() { return width * height; } }; // 派生 Circle class Circle: public Shape { private: float radius; public: Circle(float r) { radius = r; } // 实现 Shape 中的纯虚函数 float calcArea() { return 3.14 * radius * radius; } }; int main() { // 创建对象 Shape *shape; Rectangle rec(3, 4); Circle cir(5); // 调用函数 shape = &rec; cout << "矩形的面积:" << shape->calcArea() << endl; shape = &cir; cout << "圆形的面积:" << shape->calcArea() << endl; return 0; } ``` 在这个示例代码中,我们首先定义了一个抽象 Shape,其中有一个纯虚函数 calcArea(),这个函数用于计算图形的面积。然后我们定义了两个派生 Rectangle 和 Circle,它们分别实现了 calcArea() 函数。最后在 main() 函数中,我们创建了 Shape 型的指针 shape,分别指向 Rectangle 和 Circle 对象,并调用 calcArea() 函数计算面积。 需要注意的是,抽象是不能被实例化的,只有通过派生来实现它的纯虚函数才能被实例化。同时,派生在实现纯虚函数时,必须使用 virtual 关键字来声明。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值