题目描述:
乎乎学习了面向对象程序设计,他看到以下正方体类(Cube)的声明程序,请帮他实现该类。并在main函数中完成以下应用,通过输入长宽高创建一个正方体对象c1, 并用c1通过拷贝构造函数创建c2,c2的长宽高分别为c1长宽高的十分之一,然后通过指向c2的指针p调用成员函数输出c2对象的相关信息,详见输出样例。
#include <iostream>
using namespace std;
class cube
{
public:
Cube(int, int,int);
cube(cube &);
~cube();
int computeBottomArea();
int computeVolumn();
int getHeigth();
void setHeigth(int);
int getwidth();
void setwidth(int);
int getLength();
void setLength(int);
private:
int height;
int width;
int length;
};
输入描述:
一行,三个整数(均为10的倍数),分别表示长、宽、高。
输出描述:
输出c2对象的相关信息,详见输出样例。
示例1:
输入:
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>
#include<cstdio>
using namespace std;
typedef long long int ll;
class cube
{
private:
int height, width, length;
public:
cube()
{
height = width = length = 0;
cout << "Parameter constructor is called.\n";
}
cube(int height, int width, int length)
{
this->height = height;
this->width = width;
this->length = length;
}
cube(const cube&p)
{
height = p.height / 10;
width = p.width / 10;
length = p.length / 10;
cout << "Copy constructor is called.\n";
}
void set_cube(int length, int width, int height)
{
this->height = height;
this->width = width;
this->length = length;
}
void get_cube()
{
printf("The length of c2 is %d.\n", length);
printf("The width of c2 is %d.\n", width);
printf("The heigth of c2 is %d.\n", height);
printf("The bottom area of c2 is %lld.\n",(ll) length*width);
printf("The volumn of c2 is %lld.\n", (ll)length*width*height);
}
~cube()
{
cout << "Deconstructor is called.\n";
}
};
int main()
{
int l, w, h;
cin >> l >> w >> h;
cube c1;
c1.set_cube(l, w, h);
cube c2 = c1;
c2.get_cube();
return 0;
}