[英]How to change a value in a member function within a class?
我正在尝试更改已传递到我的SwimmingPool类中的值。 我正在尝试将长度,深度和宽度值相乘,以获得我的能力值。 但是,在尝试使用Capacity成员函数执行此操作的地方,它返回一个垃圾值。 我认为我的语法是正确的,所以我不知道为什么我会得到垃圾值。 下面是我的代码。
这是我的实现文件。
#include <iostream>
#include "SwimmingPoolHeader.h"
using namespace std;
int main()
{
swimmingPool len;
swimmingPool wid;
swimmingPool dep;
swimmingPool cap;
int length;
int width;
int depth;
cout << "Please enter the length of the pool." << endl;
cin >> length;
len.setLength(length);
cout << "Please enter the width of the pool." << endl;
cin >> width;
wid.setWidth(width);
cout << "Please enter the depth of the pool." << endl;
cin >> depth;
dep.setDepth(depth);
cout << "The capacity of the pool is " << cap.capacity() << endl;
system("pause");
return 0;
}
这是我的头文件。
class swimmingPool {
public:
void setLength(int l)
{
length = l;
}
int getLength()
{
return length;
}
void setWidth(int w)
{
width = w;
}
int getWidth()
{
return width;
}
void setDepth(int d)
{
depth = d;
}
int getDepth()
{
return depth;
}
int capacity()
{
return length * depth * width;
}
private:
int length;
int width;
int depth;
};
你知道什么是构造函数吗? 为什么在创建SwimmingPool对象时不添加长度,宽度和深度参数?
swimmingPool(int l = 0, int w = 0, int d = 0) : length(l), width(w), depth(d) {}
然后,您可以创建一个游泳游泳池,如下所示:
swimmingPool pool(6, 7, 8);
您可能想要用以下内容替换main()
int main()
{
int length, width, depth;
cout << "Please enter the length of the pool." << endl;
cin >> length;
cout << "Please enter the width of the pool." << endl;
cin >> width;
cout << "Please enter the depth of the pool." << endl;
cin >> depth;
swimmingPool pool;
pool.setLength(length);
pool.setWidth(width);
pool.setDepth(depth);
cout << "The capacity of the pool is " << pool.capacity() << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.