简体   繁体   English

class 内部还是外部声明?

[英]Declaration inside class or outside?

Given the following functions:给定以下功能:

1) 1)

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

2) 2)

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

Which take a scalar and adds it to every member in the Matrix, Should I declare them outside the class (like what is shown above) or inside my class?它采用标量并将其添加到矩阵中的每个成员,我应该在 class 之外(如上所示)还是在我的 class 内声明它们?

In collage they thought as that if we need it to work in both directions (symmetrical behaviour) we declare it out but here it's a little bit complicated...在拼贴画中,他们认为如果我们需要它在两个方向上工作(对称行为) ,我们将其声明出来,但在这里它有点复杂......

Function 1 can be written inside the class, as a member function, but function 2 must be written as a non-member function, since the left hand side is not a IntMatrix . Function 1 can be written inside the class, as a member function, but function 2 must be written as a non-member function, since the left hand side is not a IntMatrix .

I would suggest writing a operator+= that takes an int as a member function.我建议编写一个将int作为成员 function 的operator+= Then you can easily call that from both operator+ , which you can write as non-members.然后,您可以轻松地从两个operator+调用它,您可以将其编写为非成员。

So your operator+ (as non-members) would look like this:所以你的operator+ (作为非成员)看起来像这样:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM