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.

2
  • 1
    Don't use arrays, use vectors. Commented Nov 6, 2018 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. Commented Nov 6, 2018 at 23:42

1 Answer 1

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);
    }
    // ...
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.