将一个类对象数组添加到一个主类对象中

时间:2013-12-06 20:16:27

标签: c++ arrays class pointers reference

对于一个项目,我必须创建一个具有英尺和英寸变量的类,并且有一个方法可以将这些变量从对象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.好像添加功能不起作用,我不太清楚我甚至不明白我做了什么。根据我的想法,它正在创建一个新的obejct,将引用的对象中的变量添加到创建的对象中,注释掉的部分是我刚刚拿出的部分,稍后会添加,然后返回物体。当我在主源文件中调用该函数时,它会将对象new_total设置为等于对象0,1,2,3和4的总和。我是关闭还是关闭实际发生的事情?我还应该解释一下,我只编程了大约一年,这对我来说真的很有趣,但有时候自然很难,而且我仍然试图掌握c ++中的类的想法。

2 个答案:

答案 0 :(得分:0)

问题是你在添加时从不使用实例变量。相反,你总是从一个刚刚铸造的物体开始。试试这个:

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

答案 1 :(得分:0)

我已经完成了一些代码播放,看起来这行不正确:

CDistance total;

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

CDistance total = *this;

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

相关问题