这段代码有什么错误?#include<iostream> using namespace std; class Box //声明类Box { public: Box(int h = 10, int w = 10, int len = 10); //在声明构造函数Box时指定默认参数 int volume(); //声明成员函数volume private: int height; //高 int width; //宽 int length; //长 }; Box::Box(int h, int w, int len) //在定义Box函数时可以不指定默认参数 { height = h; width = w; length = len; } int Box::volume() //调用类Box中的volume()函数,计算体积 { return(height * width * length); } int main() { Box box1; //没有给定实参 cout << "The volume of box1 is " << box1.volume() << endl; Box box2(15); //给了一个实参 cout << "The volume of box2 is " << box2.volume() << endl; Box box3;(15, 30); //给了两个实参 cout << "The volume of box3 is " << box3.volume() << endl; Box box4;(15, 30, 20); //给了三个实参 cout << "The volume of box4 is " << box4.volume() << endl; return 0; }
时间: 2024-01-03 20:04:51 浏览: 34
这段代码有两个错误:
1. 在第25行和第27行中,Box对象的构造函数调用语句应该使用圆括号将实参括起来,而不是使用逗号隔开。
2. 在第31行中,应该将分号去掉。
修改后的代码如下:
```
#include <iostream>
using namespace std;
class Box {
public:
Box(int h = 10, int w = 10, int len = 10);
int volume();
private:
int height;
int width;
int length;
};
Box::Box(int h, int w, int len) {
height = h;
width = w;
length = len;
}
int Box::volume() {
return (height * width * length);
}
int main() {
Box box1;
cout << "The volume of box1 is " << box1.volume() << endl;
Box box2(15);
cout << "The volume of box2 is " << box2.volume() << endl;
Box box3(15, 30);
cout << "The volume of box3 is " << box3.volume() << endl;
Box box4(15, 30, 20);
cout << "The volume of box4 is " << box4.volume() << endl;
return 0;
}
```