返回函数内部的一整类信息
Returning a whole class of information inside a function
所以我一直在开发一个程序,其中有一个名为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;
}
相关文章:
- 在类构造函数中传递对外部函数的引用
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- 将自由函数绑定为类成员函数
- 带有类的函数指针
- 如何在qt中从另一个类调用函数
- 具有enable_if外部类原型的模板类构造函数定义
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 自动重复 extern "C"函数中的类构造函数采用的相同参数
- C++ 继承:将子类传递给需要基类的函数并获取子类行为
- 类的前向声明之后的类成员函数定义,在类声明之前
- 模板化类构造函数的模板实例化
- 从类成员函数到类 C 函数指针的转换
- C++派生的类构造函数
- 在类构造函数中使用结构变量
- 在类构造函数中定义结构变量的参数
- 如何定义一个没有重复代码的继承的 const 类成员函数?
- 为什么下面的模板化类成员函数无法编译?
- 返回函数内部的一整类信息
- 使用类和函数来提供有关矩形的信息
- 类和函数的麻烦里面有更多的信息