如何更改类中成员函数中的值

How to change a value in a member function within a class?

本文关键字:函数 成员 何更改      更新时间:2023-10-16

我正在尝试更改已传递到我的游泳池类的值。我正在尝试将长度、深度和宽度值相乘,以获得我的容量值。但是,当我尝试使用容量成员函数来执行此操作时,它会返回一个垃圾值。我认为我的语法是正确的,所以我是为什么我不确定为什么我会得到垃圾值。下面是我的代码。

这是我的实现文件。

#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;
}