简体   繁体   English

C ++-在C ++类中初始化私有数组

[英]C++ - Initialize private array in c++ class

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. 我尝试使用Google,但没有找到任何解决方案。

Here's my code: 这是我的代码:

Foo.h oo

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

Foo.cpp 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 ? 这是我的问题-如何将数组保存到f中

Seems like using pointer ( *f.arr = array; ) doesn't acturally change the arr . 好像使用指针( *f.arr = array; )不会实际改变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. 但是Visual Studio 2017表示未初始化数组。


I also tried this solution , but VS says cannot modify the array in this scope. 我也尝试了这种解决方案 ,但是VS说无法在此范围内修改数组。

Please help. 请帮忙。 Thank you in advance. 先感谢您。

#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);
    }
    // ...
};

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

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