【问题标题】:How do I overload the + operator to add 2 objects of same class (each with 3 numbers) to create 1 object with all 6 numbers?如何重载 + 运算符以添加 2 个相同类的对象(每个对象有 3 个数字)以创建 1 个具有所有 6 个数字的对象?
【发布时间】:2015-11-23 15:32:24
【问题描述】:

我目前正在做一个编程项目,其中我声明了一个名为 Statistician 的类的 2 个对象。这些对象称为 s1 和 s2。每个对象使用一个函数将 3 个 double 类型的值读入序列中。然后,对于每个序列,我计算并打印结果:序列长度、最后输入的数字、序列总和、算术平均值、最小数字、最大数字(每个计算都有自己的函数,它返回值。

我目前正在尝试重载 + 运算符,以便我可以将两个序列(每个序列都有 3 个数字)一起添加到具有所有 6 个值的第三类对象中。然后,我希望能够在这个新类上执行我上面列出的计算。如何重载 + 运算符来执行此任务?

到目前为止我所拥有的:

Statistician operator +(const Statistician&)
{
//Postcondition: the sum of all numbers in sequences s1 and s2 is returned
}

另外,有人告诉我,我应该将其设为友元函数,以访问我在类中声明的变量。如何正确声明朋友函数以便它有权执行此操作?

【问题讨论】:

  • 请提供完整的类定义。这会很有帮助。
  • 您为 operator+ 指定了类成员函数签名。对于成员函数,友元声明没有意义。

标签: c++ operator-overloading operator-keyword friend friend-function


【解决方案1】:

您只需在 Internet 上查找(使用您喜欢的搜索引擎)即可了解如何声明朋友函数:http://en.cppreference.com/w/cpp/language/friend

class Statistician
{
   friend Statistician operator+(const Statistician&, const Statistician&);
   // other stuff
}

而且,我只能给出一个骨架。如果您将Statistician 的类定义和实现添加到您的问题中,将会很有帮助。

Statistician operator+(const Statistician& left, const Statistician& right)
{
    Statistician result;
    // put your code here to add data from "left" and "right" into "result"        
    return result;
}

【讨论】:

  • friend 声明与非成员重载一起使用,如果要成为成员函数,则第二个示例缺少 Statistician::
  • 应该是我的非会员...修复它。 (从问题本身复制和过去的错误)
  • 由于相关信息不足,无法完成第二个示例。等待问题更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-27
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多