构造函数 (C++) 中的初始化静态数组

Initialization static array in constructor (C++)

本文关键字:初始化 静态 数组 C++ 构造函数      更新时间:2023-10-16

我有这个类

class Dot
{
    public:            // Methods
    Dot();                                       // Default Constructor
    Dot (int dot [], int k);                     // Constructor
    ~Dot();                                      // Destructor
    int getDot();                                // Get Function
    void setDot (int dot []);                    // Set Function
    void PrintDot ();                            // Print Dot

    private:          // Attributes
    int m_k;
    int m_dot [];
};

我想编写默认构造函数

Dot::Dot(): m_k(2), m_dot[] ({0,0})              // Compilation Error

Dot::Dot (int dot [], int k)
{     
       m_k=k;
       m_dot [k]= dot [k];
}   

但我不知道如何将静态数组m_dot初始化为默认构造函数。它不起作用...由于第二个构造函数,我无法像常量一样初始化它(可以修改值 k 和那里的数组点)

谢谢

您尝试使用的数组不是静态数组,因为条目数由您在构造函数中指定的k参数确定。 该数组实际上是动态的,因此您可以使用C++提供的功能,这就是std::vector

#include <vector>
class Dot
{
    public:            // Methods
        Dot();                                       // Default Constructor
        Dot (int dot [], int k);                     // Constructor
       ~Dot();                                      // Destructor
        int getDot();                                // Get Function
        void setDot (int dot []);                    // Set Function
        void PrintDot ();                            // Print Dot
    private:          // Attributes
        std::vector<int> m_dot;
};

然后构造函数将如下所示:

Dot::Dot(): m_dot(2,0) {}
Dot::Dot(int dot[], int k) : m_dot(dot, dot+k) {}

请注意,向量基本上是动态数组的包装器。 另请注意,不再需要m_k,因为m_dot.size()会告诉您条目数。