在类内部还是外部的声明?

问题描述 投票:0回答:1

提供以下功能:

1)

IntMatrix operator+(const IntMatrix &matrix, int scalar);

2)

IntMatrix operator+(int scalar, const IntMatrix &matrix);

哪个使用标量并将其添加到Matrix中的每个成员,我应该在类之外(如上面所示)或在类内部声明它们?

在拼贴中,他们认为如果我们需要它在两个方向上都起作用(对称行为)我们将其声明出来,但是这里有点复杂...

c++ class operator-overloading
1个回答
1
投票

函数1可以作为成员函数编写在类内部,但是函数2必须作为非成员函数编写,因为左侧不是IntMatrix

我建议编写一个以operator+=作为成员函数的int。然后,您可以轻松地从两个operator+中调用它,您可以将其写为非成员。

因此您的operator+(作为非成员)将如下所示:

IntMatrix operator+(IntMatrix matrix, int scalar) {
  return matrix += scalar;
}

IntMatrix operator+(int scalar, IntMatrix matrix) {
  return matrix += scalar;
}
© www.soinside.com 2019 - 2024. All rights reserved.