【问题标题】:How to change a value in a member function within a class?如何更改类中成员函数中的值?
【发布时间】:2018-01-28 00:17:30
【问题描述】:

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

这是我的实现文件。

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

【问题讨论】:

  • /OT 有趣的个人资料。您是如何保持 1 分代表、1 枚金牌徽章、3 枚银牌和 5 枚铜牌的?除此之外,您的问题题外话,对不起。
  • 您的班级有 4 个不同的实例。你要一个吗。您可以考虑添加一个构造函数来将您的成员变量初始化为 0;
  • 在我看来您需要a couple of good beginners books 才能阅读。
  • 不要误会,但你的设计似乎依赖于巫术。忽略你有三个不同的游泳池,每个游泳池都有一个一维这一事实,你有第四个游泳池,你似乎认为它会被某种同情的魔法赋予这些价值,也许当编译器使用它的 AGI 从变量的名称(以及它对游泳池的知识)推断您的意图。尽管这个程序很简单,但它依赖于您忽略学习的一些软件基本原理。在尝试这个之前,您必须掌握更简单的练习。
  • 你的程序相当于测量一个水池的长度,开车到另一个地方测量另一个水池的宽度,去别的地方测量另一个水池的深度,最后访问第四个池并猜测其总容量。可能您的意思是只处理一个游泳池,这意味着您应该只有一个 swimmingPool 对象。

标签: c++ function class member


【解决方案1】:

你知道什么是构造函数吗?为什么不在创建swingPool对象的时候加上长宽深参数呢?

swimmingPool(int l = 0, int w = 0, int d = 0) : length(l), width(w), depth(d) {}

然后,您可以像这样创建一个游泳池:

swimmingPool pool(6, 7, 8);

【讨论】:

    【解决方案2】:

    你可能想用类似的东西替换你的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;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多