#include <iostream> using namespace std; class Box{ public: Box(int,int,int); void volume(); private: int height,width,length; }; Box::Box(int h,int w,int len){ height=h; width=w; length=len; } void Box::volume(){ cout<<(height*width*length); } int main(){ Box box1(12,25,30); cout<<"The volume of box1 is"<<volume(box1); Box box2(15,30,21); cout<<"The volume of box1 is"<<volume(box2); return 0; } 为什么说volume()没有呗定义
时间: 2024-01-16 15:03:17 浏览: 22
代码中出现了两个问题:
1. 在主函数中调用 `volume` 函数时,需要使用 `box1.volume()` 和 `box2.volume()` 进行调用,而不是 `volume(box1)` 和 `volume(box2)`。
2. 编译器报错说 `volume()` 函数未定义,是因为 `volume()` 函数的定义部分没有被实现。你需要在 `Box` 类的实现文件中添加 `volume()` 函数的实现部分,例如:
```
void Box::volume(){
cout << (height * width * length) << endl;
}
```
修改后的代码如下:
```
#include <iostream>
using namespace std;
class Box{
public:
Box(int, int, int);
void volume();
private:
int height, width, length;
};
Box::Box(int h, int w, int len){
height = h;
width = w;
length = len;
}
void Box::volume(){
cout << (height * width * length) << endl;
}
int main(){
Box box1(12, 25, 30);
cout << "The volume of box1 is ";
box1.volume();
Box box2(15, 30, 21);
cout << "The volume of box2 is ";
box2.volume();
return 0;
}
```
输出结果:
```
The volume of box1 is 9000
The volume of box2 is 9450
```
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)