Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

c++ - 在A类C ++中初始化2D数组(Initializing 2D Array in A Class C++)

I am trying to initialize nums 2D array in a Class Construct .

(我正在尝试在Class Construct初始化nums 2D数组。)

I am using the default constructor to initialize it but since it has already been created I am unable to.

(我正在使用默认构造函数对其进行初始化,但是由于已经创建了它,所以无法进行初始化。)

I cannot initialize it in the class either.

(我也不能在类中初始化它。)

I have tried initializing each element manually and it works but I want to just initialize nums in one line.

(我尝试过手动初始化每个元素,并且它可以工作,但是我只想在一行中初始化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; 
} 

I have tried nums[1][0] = 5 ... but that is not very efficient.

(我已经尝试过nums[1][0] = 5 ...但这不是很有效。)

Any feedback would be great.

(任何反馈将是巨大的。)

  ask by Gorav Soni translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use initializer list

(使用初始化列表)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...