0

I'm having a problem of storing data into the private array in a class.

I tried to Google and didn't find any solution.

Here's my code:

Foo.h

class Foo {
private:
    int arr[10];
    double d;
public:
    Foo::Foo(double d) {
        this->d = d;
    }
    // ...
};

Foo.cpp

int main() {
    double d = 123.456;
    int array[10];
    // Getting data from user input by for-loop 10 times.

    Foo f = Foo(d);

And here's my problem -- how to save the array into the f?

Seems like using pointer (*f.arr = array;) doesn't acturally change the arr.


I tried this solution by adding

class Foo {
// ...
Public:
    Foo::Foo(int arr_, double d_) : arr_(new int[10]), d_(d) { };

But the Visual Studio 2017 says the array is not initialized.


I also tried this solution, but VS says cannot modify the array in this scope.

Please help. Thank you in advance.

CFSO6459
  • 85
  • 7
  • 1
    Don't use arrays, use vectors. –  Nov 06 '18 at 23:41
  • You should ask for an array of integers in the constructor, not a single integer. And then copy all values into array. Don't use new because Foo::arr is already allocated. –  Nov 06 '18 at 23:42

1 Answers1

2
#include <algorithm>  // std::copy()
#include <iterator>   // std::size()

class Foo {
private:
    int arr[10];
    double d;
public:
    Foo(double d, int *data)
    : d{ d }
    {
        std::copy(data, data + std::size(arr), arr);
    }
    // ...
};
Swordfish
  • 12,971
  • 3
  • 21
  • 43