注册 登录
编程论坛 C++教室

编写一个名为door的类,其中定义两个公有浮点型成员变量height和width, 其赋其缺省值分别为 2.0 和 1.5

baolis 发布于 2022-11-21 09:06, 501 次点击
编写一个名为door的类,其中定义两个公有浮点型成员变量height和width,
其赋其缺省值分别为 2.0 和 1.5。改写其构造和析构函数。构造对象时,可以
给成员变量 height 和 width 赋新值,并且输出字符串“The door is created…”。
析构对象时,输出“The door is destroyed…”。类中定义两个成员函数,分别求
出 door 的周长 perimeter 和面积 acreage。
要求写出包含主程序和实例化对象在内的完整的程序。
3 回复
#2
rjsp2022-11-21 09:50
哪里不会你要讲出来,而不是全抄

程序代码:
#include <iostream>

class door
{
public:
    double height;
    double width;

    explicit door( double height=2.0, double width=1.5 ) : height(height), width(width)
    {
        std::cout << "The door is created…\n";
    }
    door( const door& rhs ) :  height(rhs.height), width(rhs.width)
    {
        std::cout << "The door is created…\n";
    }
    door( door&& rhs ) noexcept = default;

    ~door()
    {
        std::cout << "The door is destroyed…\n";
    }

    double perimeter() const noexcept
    {
        return 2*(height+width);
    }
    double acreage() const noexcept
    {
        return height*width;
    }
};

std::ostream& operator<<( std::ostream& os, const door& rhs )
{
    return os << "{ height=" << rhs.height << ", width=" << rhs.width << " }";
}

using namespace std;

int main( void )
{
    {
        door a;
        cout << a << endl;

        door b{ 3, 4 };
        cout << b << endl;

        door c = b;
        cout << b << endl;

        cout << "perimeter: " << c.perimeter() << endl;
        cout << "acreage: " << c.acreage() << endl;
    }
}
#3
baolis2022-11-21 11:18
回复 2楼 rjsp
#4
baolis2022-11-21 14:10
回复 2楼 rjsp
1