【问题标题】:Initializing 2D Array in A Class C++在 C++ 类中初始化二维数组
【发布时间】:2019-12-01 11:16:52
【问题描述】:

我正在尝试在 Construct 类中初始化 nums 二维数组。我正在使用默认构造函数来初始化它,但由于它已经创建,我无法这样做。我也不能在课堂上初始化它。我已经尝试手动初始化每个元素并且它可以工作,但我只想在一行中初始化nums

#include <iostream> 
using namespace std; 

class Construct { 
public: 
    int nums[3][3]; 

    // Default Constructor 
    construct() 
    { 
        int nums[3][3] = {{4,5,42,34,5,23,3,5,2}}
    } 
}; 

int main() 
{ 

    Construct c; 
    cout << "a: " << c.nums[1][0] << endl 
        << "b: " << c.nums[0][1]; 
    return 1; 
} 

我试过了 nums[1][0] = 5 ...但这不是很有效。任何反馈都会很棒。

【问题讨论】:

  • 你只是声明了一个与成员变量同名的局部变量,一旦你退出函数,它就会消失。顺便说一句,您需要使用确切的类名才能使此函数用作构造函数。 BTW 2,{{4,5,42,34,5,23,3,5,2}} 的尺寸不是 3 x 3。
  • 为构造函数使用成员初始化列表。 en.cppreference.com/w/cpp/language/initializer_list

标签: c++ arrays initialization


【解决方案1】:

使用初始化列表

Construct(): nums {{4,5,42},{34,5,23},{3,5,2}}
{ }

【讨论】:

    【解决方案2】:

    如果您希望能够使用自定义值初始化您的类,您将需要提供一个构造函数,该构造函数将某种容器作为参数并使用它来初始化您的数组:i.e. Construct(const atd::array&lt;int, 6&gt;&amp;)

    但为了避免重写已初始化数组的所有值的开销,您需要使用 Pack 扩展。

    这是一个自定义的类模板,它提供了这样的构造函数:

    #include <utility>
    #include <array>
    
    // typename of an underlying array, sz0 and sz1 - array dimensions
    template <typename T, size_t sz0, size_t sz1,
        class = decltype(std::make_index_sequence<sz0 + sz1>())>
        class Construct_;
    
    // expanding a Pack of indexes to access std::array's variables
    template <typename T, size_t sz0, size_t sz1,
        size_t ... indx>
        class Construct_<T, sz0, sz1, 
            std::index_sequence<indx...>>
    {
    // make it private or use a struct instead of a class
        T nums_[sz0][sz1];
    
    public:
    
        // nums_ is initialized with arr's values. No additional copies were made
        Construct_(const std::array<T, sz0 + sz1> &arr)
            : nums_{ arr[indx] ... }
        {}
    
    };
    
    using Construct33int = Construct_<int, 3, 3>;
    
    int main()
    {
        std::array<int, 6> arr{ 4, 8, 15, 16, 23, 42 };
        Construct33int c{ arr };
    
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-30
      • 2018-08-21
      • 2021-04-04
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2022-01-08
      • 2021-10-02
      相关资源
      最近更新 更多