类的练习1 —— 打印圆的面积

在面向对象程序设计中,一个对象表示现实世界中一个独一无二的实体。

相同类型的对象用一个通用的类来定义。一个是指一个模板、蓝图或者约定,定义了对象具有什么样的数据域函数

一个对象就是一个类的实例,我们可以创建一个类的多个实例。

 

对于类模板和对象的图示,我们可以用UML(Unified Modeling Language, 统一建模语言)表示法将其标准化。

 

首先,我们画一个圆类的UML类图。

  • 表格分成三部分:类名、数据域、构造函数和函数
  • 加号"+"表示公有域,函数名(参数类型):返回值

 

练习1:创建三个半径不同的“圆”对象,打印输出每个对象的半径和面积,并且修改第二个对象的半径并输出。

参考代码:

#include "pch.h"
#include <iostream>
using namespace std;

class Circle
{
public:
	double radius;
	
	Circle()	//默认的构造函数
	{
		radius = 1;
	}
	
	Circle(double newRadius)	//有参数的构造函数。
	{
		radius = newRadius;
	}

	double getArea()
	{
		return radius * radius * 3.14159;
	}
};

int main()
{
	Circle circle1(1.0);
	Circle circle2(25);
	Circle circle3(125);
	
	cout << "The area of the circle of radius " << circle1.radius << " is " << circle1.getArea() << endl;
	cout << "The area of the circle of radius " << circle2.radius << " is " << circle2.getArea() << endl;
	cout << "The area of the circle of radius " << circle3.radius << " is " << circle3.getArea() << endl;

	circle2.radius = 100;
	cout << "The area of the circle of radius " << circle2.radius << " is " << circle2.getArea() << endl;

	return 0;
}

 

答案:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值