c++week4设计并实现一个矩形类Rectangle

2021/10/1 14:40:52

本文主要是介绍c++week4设计并实现一个矩形类Rectangle,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

 

 

#include <iostream>
#include <iomanip>

// 矩形类Rectangle的定义和实现
// 补足代码
// ×××
class Rectangle
{
public:
    Rectangle();
    Rectangle(int l, int w);
    Rectangle(const Rectangle &x);

    double len();
    double wide();
    double area();
    double circumference();
    void resize(double times);
    void resize(double l_times, double l_);

    ~Rectangle() = default;

private:
    double lenth, width;
};

Rectangle::Rectangle()
{
    lenth = 2.0;
    width = 1.0;
}
Rectangle::Rectangle(int l, int w)
{
    lenth = l;
    width = w;
}
Rectangle::Rectangle(const Rectangle &x)
{
    lenth = x.lenth;
    width = x.width;
}
double Rectangle::len()
{
    return lenth;
}

double Rectangle::wide()
{
    return width;
}
double Rectangle::area()
{
    return lenth*width;
}
double Rectangle::circumference()
{
    return (lenth + width) * 2;
}
void Rectangle::resize(double times)
{
    lenth *= times;
    width *= times;
}
void Rectangle::resize(double l_times, double w_times)
{
    lenth *= l_times;
    width *= w_times;
}



// 普通函数, 用于输出矩形信息
void output(const Rectangle &rect) {
    using namespace std;
    Rectangle a = rect;
    cout << "矩形信息: \n";
              // 控制输出格式:以浮点数形式输出、小数部分保留两位
    // 补足代码:分行输出矩形长、宽、面积、周长
    cout << fixed << setprecision(2);
    cout << "长:    " << left << a.len() << endl;
    cout << "宽:    " << left << a.wide() << endl;
    cout << "面积:  " << left << a.area() << endl;
    cout << "周长:  " << left << a.circumference() << endl;
    cout << endl;
 }


// 主函数,测试Rectangle类
int main()
{
    Rectangle rect1;        // 默认构造函数被调用
    output(rect1);

    Rectangle rect2(15, 5);     // 带有两个参数的构造函数被调用
    output(rect2);

    Rectangle rect3(rect1);     // 复制构造函数被调用
    rect3.resize(3);            // 矩形rect3的长和宽同时缩放2倍
    output(rect3);

    rect3.resize(10, 2);         // 矩形rect3的长缩放5倍, 宽缩放2倍
    output(rect3);

    system("pause");
}



这篇关于c++week4设计并实现一个矩形类Rectangle的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程