请在下列代码基础上增加或修改如下功能: 1)带默认值或者重载的普通构造函数 2)析构函数(增加一条输出语句做测试即可) 3)将3个立方柱定义成对象数组并初始化 4)this指针请显示使用 #include <iostream> using namespace std; class cube//定义类 { public: //构造函数重载或者带默认值,建议二选一,允许对象传参和不传参都可以执行 //析构函数 void setvalue();//输入数据成员值 float volume();//计算体积 private: float length;//长、宽、高数据成员,定义成私有数据 float width; float height; }; void cube::setvalue()//显示使用this指针 { cout<<"请输入长方柱的长、宽、高"<<endl; cin>>length>>width>>height; } float cube::volume()//类外定义函数,请显示使用this指针 { return length*width*height; } int main() { cube c1,c2,c3;//修改成对象数组并初始化 c1.setvalue(); cout<<"该长方柱的体积为:"<<c1.volume()<<""<<endl; c2.setvalue(); cout<<"该长方柱的体积为:"<<c2.volume()<<""<<endl; c3.setvalue(); cout<<"该长方柱的体积为:"<<c3.volume()<<""<<endl; return 0; }
时间: 2023-06-01 17:01:53 浏览: 44
1)增加带默认值的构造函数和重载的普通构造函数:
```
class Cube {
private:
double length;
double width;
double height;
public:
// 默认构造函数
Cube() {
length = 0;
width = 0;
height = 0;
}
// 带参数构造函数
Cube(double len, double wid, double hei) {
length = len;
width = wid;
height = hei;
}
// 带默认值的构造函数
Cube(double len = 0, double wid = 0, double hei = 0) {
length = len;
width = wid;
height = hei;
}
~Cube() {
cout << "调用了析构函数" << endl;
}
void setLength(double len) {
this->length = len;
}
void setWidth(double wid) {
this->width = wid;
}
void setHeight(double hei) {
this->height = hei;
}
double getVolume() {
return this->length * this->width * this->height;
}
};
```
2)增加析构函数:
```
~Cube() {
cout << "调用了析构函数" << endl;
}
```
3)将3个立方柱定义成对象数组并初始化:
```
Cube cubes[3] = {
Cube(1, 2, 3),
Cube(2, 3, 4),
Cube(3, 4, 5)
};
```
4)使用this指针:
```
void setLength(double len) {
this->length = len;
}
void setWidth(double wid) {
this->width = wid;
}
void setHeight(double hei) {
this->height = hei;
}
double getVolume() {
return this->length * this->width * this->height;
}
```