17.封装—定义正方体类

文章讲述了在面向对象编程中,如何声明和实现一个立方体类Cube,包括参数构造函数、拷贝构造函数以及成员函数get_Cube,用于计算并输出立方体的尺寸和体积。在main函数中,通过输入创建c1和c2对象,并展示拷贝构造函数的应用。
摘要由CSDN通过智能技术生成

题目:

乎乎学习了面向对象程序设计,他看到以下正方体类(Cube)的声明程序,请帮他实现该类。并在main函数中完成以下应用,通过输入长宽高创建一个正方体对象c1, 并用c1通过拷贝构造函数创建c2,c2的长宽高分别为c1长宽高的十分之一,然后通过指向c2的指针p调用成员函数输出c2对象的相关信息,详见输出样例。

输入:

10 20 30

输出:

Parameter constructor is called.

Copy constructor is called.

The length of c2 is 1.

The width of c2 is 2.

The heigth of c2 is 3.

The bottom area of c2 is 2.

The volumn of c2 is 6.

Deconstructor is called.

Deconstructor is called.

代码:

#include<iostream>
using namespace std;
class Cube
{
    private:
int height; int width; int length;
    public:
Cube(int a,int b,int c):length(a),width(b),height(c)
{cout<<"Parameter constructor is called."<<endl;
 cout<<"Copy constructor is called."<<endl;}
Cube(Cube &b)
{
    length=b.length/10;
    width=b.width/10;
    height=b.height/10;
    
}
~Cube(){cout<<"Deconstructor is called."<<endl;}
void get_Cube()
{
    cout<<"The length of c2 is "<<length<<"."<<endl;
    cout<<"The width of c2 is "<<width<<"."<<"\n";
    cout<<"The heigth of c2 is "<<height<<"."<<"\n";
    cout<<"The bottom area of c2 is "<<length*width<<"."<<"\n";
    cout<<"The volumn of c2 is "<<length*width*height<<"."<<"\n";
}
};
int main()
{
    int a,b,c;
    cin>>a>>b>>c;
    Cube c1(a,b,c);
    Cube c2=c1;
    c2.get_Cube();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值