题目描述
【问题描述】声明一个Circle类,有数据成员Radius(半径)、成员函数GetArea(),并满足以下要求。
(1)需要定义和合理的构造函数。
(2)使用函数重载方式重载成员函数,当输入一个参数时,被认作创建圆,并认为输入圆半径,计算并返回圆的面积;当输入两个参数时,认为创建一个圆,计算并返回圆环的面积;
(3)其他自行界定。
(4)编写合适的主函数,构造一个Circle的对象进行对象创建,以及成员函数的测试。
样例1:
【输入形式】10
【输出形式】
the circle is created!
the area is:314
样例2:
【输入形式】10 5
【输出形式】
the circle is created!
the ring's area is:235.5
解题思路
本体是C++的面向对象相关题,定义类操作等等,首先对与不同的用户输入根据这个写出重载函数即可,根据输入一个数之后的下一个字符为空格还是换行判断输入数个数即可。
源代码
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class Circle {
private:
int Radius1, Radius2;
public:
void GetArea(int a) {
Radius1 = a;
double res = 3.14 * Radius1 * Radius1;
cout << "the circle is created!\n" << "the area is:";
printf("%g", res);
}
void GetArea(int a, int b) {
Radius1 = a;
Radius2 = b;
double res = 3.14 * Radius1 * Radius1 - 3.14 * Radius2 * Radius2;
cout << "the circle is created!\n" << "the ring's area is:";
printf("%g", res);
}
};
int main(){
Circle circle;
int arr[2], i = 1, a, b;
char c;
scanf("%d", &a);
arr[0] = a;
c = getchar();
if (c == ' ') {
scanf("%d", &b);
arr[1] = b;
i = 2;
}
switch (i) {
case 1:
circle.GetArea(arr[0]);
break;
case 2:
circle.GetArea(arr[0], arr[1]);
break;
}
return 0;
}
总结
对于刚接触到面向对象的初学者有一定难度,主要在于理解面向对象内涵。