返回函数内部的一整类信息

Returning a whole class of information inside a function

本文关键字:类信息 函数 内部 返回      更新时间:2023-10-16

所以我一直在开发一个程序,其中有一个名为CDistance的类,它就是

class CDistance
{
private:
    int feet, inches;
public:
    CDistance();
    CDistance(int, int);
    void setDist();
    void printDist() const;
    CDistance add(const CDistance&) const;
};

我需要做的一部分是创建一个由5个对象组成的数组,在每个对象上设置英尺和英寸,然后在不更改原始变量的情况下将它们添加在一起。这是函数定义,正如你所看到的,它与所有常量成员一起工作,所以它需要弄清楚如何引用变量,但最重要的是,将它们返回到要返回的CDistance类型中。我应该在这个函数中创建一个新的CDistance类型来使用ref 吗

CDistance CDistance::add(const CDistance&) const
{
}

这就是我一直被卡住的地方,我对整个指针和封装协议有点困惑。我是编程新手,通过艰苦的方式学会了这一点,但如果有人能帮助我,我会非常感激

我应该在这个函数中创建一个新的CDistance类型来使用ref 吗

是的,您需要一个新的对象来修改并返回:

CDistance add(const CDistance& other) const {
    CDistance result = *this;      // Copy this object
    result.feet += other.feet;     // Add the other object...
    result.inches += other.inches; // ... to the copy
    return result;                 // Return the copy
}

请注意,这还不完整;有一个故意的错误和未知数量的意外错误,您需要自己修复。

您可以简单地从函数中return一个本地结果实例

CDistance CDistance::add(const CDistance& other) const
{
    CDistance result(*this);
    // Calculate the result using result.feet, result.inches and 
    // other.feet, other.inches
    return result;
}