長方形クラスを設計します。メンバー変数には長さと幅が含まれ、メンバー関数には周長の計算と面積の計算が含まれ、Set メソッドを使用して長さと幅を設定し、Get メソッドを使用して長さを取得します。
正方形の長さと幅
1)创建头文件。在工程主界面左上角点击 File 菜单,在弹出的 New 对话框
中选择 C/C++ Header File 选项,新建头文件命名为 Rectangle.h。用来设计长方形类。
2)编辑头文件。在弹出的 Rectangle.h 头文件中添加 Rectangle 类的代码。
步骤 a:声明程序设计所需要包含的头文件:
#include <iostream.h>
步骤 b:根据题目要求:定义长方形类:Rectangle 类:
class Rectangle
{
……
};
步骤 c:在 Rectangle 类中定义成员变量:
private:
float length; //长
float width; //宽
步骤 d:定义成员函数:
构造函数:
Rectangle(float len = 1, float wid = 1):length(len), width(wid){
}
析构函数:
~ Rectangle (){
}
//定义函数功能
计算长方形周长的成员函数:
float Perimeter(){
return 2*(length + width);
}
计算长方形面积的成员函数:
double Area() {
return length*width;
}
设置长方形长的成员函数:
void SetLength(float len)
{
length = len;
}
设置长方形宽的成员函数
void SetWidth(float wid)
{
width = wid;
}
获取长方形长的成员函数
float GetLength()
{
return length;
}
获取长方形宽的成员函数
float GetWidth()
{
return width;
}
步骤 e:程序编写示例
3)创建源文件。在工程主界面左上角点击 File 菜单,在弹出的 New 对话框
中选择 C++Source File 选项,新建头文件命名为 Rectangletest.cpp。用来测试长
方形类。
4)编辑源文件。在弹出的 Rectangletest.cpp 头文件中添加测试主程序代码。
a.详细代码:
#include "Rectangle.h" //包含 Rectangle.h 头文件
void main()
{
Rectangle Rec1, Rec2(10, 10);
cout<<"长:"<<Rec1.GetLength()<<" 宽:"<<Rec1.GetWidth()<<endl;
cout<<"周长:"<<Rec1.Perimeter()<<" 面积:"<<Rec1.Area()<<endl<<endl;
Rec1.SetLength(5);
Rec1.SetWidth(8);
cout<<"长:"<<Rec1.GetLength()<<" 宽:"<<Rec1.GetWidth()<<endl;
cout<<"周长:"<<Rec1.Perimeter()<<" 面积:"<<Rec1.Area()<<endl<<endl;
cout<<"长:"<<Rec2.GetLength()<<" 宽:"<<Rec2.GetWidth()<<endl;
cout<<"周长:"<<Rec2.Perimeter()<<" 面积:"<<Rec2.Area()<<endl<<endl;
}
#include<iostream>
using namespace std;
class CF {
//定义CF类
public:
int C;
int K;
CF()
{
}
//定义函数功能
void set(){
cout << "请输入长度" << endl;
cin >> C;
getchar();
cout << "请输入宽度" << endl;
cin >> K;
}
void get() {
cout << "长度为:" << C << endl;
cout << "宽度为:" << K << endl;
}
int ZC() {
int c;
c = 2 * (C + K);
return c;
}
int MJ() {
int c;
c = C * K;
return c;
}
~CF()
{
}
};
int main() {
int a;
int c, d;
CF m;
m.set();
cout << "--------------------------" << endl;
m.get();
cout << "--------------------------" << endl;
cout << "请选择操作:" << endl << "1:求周长" << endl << "2:求面积" << endl;
cout << "--------------------------" << endl;
while (scanf("%d", &a) != EOF) {
if (a == 1) {
cout << "周长是" << m.ZC() << endl;
}
else if (a == 2) {
cout << "面积是" << m.MJ() << endl;
}
}
return 0;
}