这是C ++的经典“带有类的C”方法。实际上,这不是任何经验丰富的C ++程序员都会写的。首先,不鼓励使用原始C数组,除非您要实现容器库。
这样的事情会更合适:
// Don't forget to compile with -std=c++17
#include <iostream>
using std::cout; // This style is less common, but I prefer it
using std::endl; // I'm sure it'll incite some strongly opinionated comments
#include <array>
using std::array;
#include <algorithm>
#include <vector>
using std::vector;
class MyClass {
public: // Begin lazy for brevity; don't do this
std::array<int, 5> arr1 = {1, 2, 3, 4, 5};
std::array<int, 5> arr2 = {10, 10, 10, 10, 10};
};
void elementwise_add_assign(
std::array<int, 5>& lhs,
const std::array<int, 5>& rhs
) {
std::transform(
lhs.begin(), lhs.end(), rhs.begin(),
lhs.begin(),
[](auto& l, const auto& r) -> int {
return l + r;
});
}
int main() {
MyClass foo{};
elementwise_add_assign(foo.arr1, foo.arr2);
for(auto const& value: foo.arr1) {
cout << value << endl; // arr1 values have been added to
}
for(auto const& value: foo.arr2) {
cout << value << endl; // arr2 values remain unaltered
}
}