簡體   English   中英

如何在類中的成員函數中更改值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM