【问题标题】:adding an array of class objects into one master class object将一组类对象添加到一个主类对象中
【发布时间】:2013-12-06 20:16:27
【问题描述】:

对于一个项目,我必须创建一个包含英尺和英寸变量的类,并且有一个方法可以将这些变量从对象 1 和对象 2 以及对象 3、4 等相加。

CDistance CDistance::add(const CDistance& yourDist) const
{
    CDistance total;
    total.feet += yourDist.feet;
    total.inches += yourDist.inches;
    /*if (total.inches > 12)
    {
        total.feet += (total.inches / 12);
        total.inches = total.inches % 12;
    }*/
    return total;
}

这是我添加的方法,这里是主源文件中的一个函数,我在其中处理每个类

void printAndAdd(const CDistance distList[], int size)
{
    CDistance new_total;
    new_total = distList[0].add(distList[1].add(distList[2].add(distList[3].add(distList[4]))));
    new_total.printDist();
}

这是我用来在屏幕上打印数据的方法

void CDistance::printDist() const
{
    cout << "Feet: " << this->feet << "\n\n";
    cout << "Inches: " << this->inches << "\n\n";
}

我曾考虑在第二行使用 for 循环,但我遇到了一些问题。每当我打印数据时,它都是 0。好像 add 函数不起作用,我不太确定我什至理解我做了什么。从我认为我正在做的事情来看,它正在创建一个新的对象,将引用对象中的变量添加到创建的对象中,注释掉的部分是我现在刚刚取出的部分,稍后会添加,然后它返回物体。当我在我的主源文件中调用该函数时,它会将对象 new_total 设置为等于对象 0、1、2、3 和 4 的总和。我是接近,还是远离实际发生的事情?我还应该解释一下,我只编程了大约一年,这对我来说真的很有趣,但有时自然会很困难,而且我仍在努力掌握 C++ 中类的概念。

【问题讨论】:

    标签: c++ arrays class pointers reference


    【解决方案1】:

    问题是您在添加时从不使用实例变量。相反,您总是从一个新铸造的对象开始。试试这个:

    CDistance CDistance::add(const CDistance& yourDist) const
    {
        CDistance total(*this);
        total.feet += yourDist.feet;
        total.inches += yourDist.inches;
    
        this->feet += yourDist.feet;
        this->inches += yourDist.inches;
        return total;
    }
    

    【讨论】:

      【解决方案2】:

      我已经对您的代码进行了一些操作,看起来这一行应该是不正确的:

      CDistance total;
      

      total 的值永远不会被初始化,因此总是会是你的默认构造函数定义的值(可能是 0/0)。因此,该调用的结果将始终以传递给输入的任何内容结束。我想你是打算这样做的:

      CDistance total = *this;
      

      这会将英尺一英寸的当前值复制到温度中,然后以下行将添加输入。像您一样通过调用链现在应该按预期连接添加。

      【讨论】:

        猜你喜欢
        • 2021-12-10
        • 1970-01-01
        • 1970-01-01
        • 2015-07-12
        • 1970-01-01
        • 1970-01-01
        • 2017-12-20
        • 2017-05-07
        • 1970-01-01
        相关资源
        最近更新 更多