构造函数 (C++) 中的初始化静态数组
Initialization static array in constructor (C++)
我有这个类
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()
会告诉您条目数。
相关文章:
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- "local scope"中的 C++ 初始化静态变量
- 虚拟成员函数的定义是否强制在同一转换单元中动态初始化静态数据成员?
- 未调用的初始化静态thread_local结构的构造函数和析构函数
- 如何在 C++ 中使用 NULL(或 0)初始化静态字符数组
- 如何从静态类函数初始化静态类对象
- C++:用IIFE线程初始化静态局部变量安全吗
- 如何在 c++ 中初始化静态类对象?
- 使用 lambda 初始化静态数组
- 使用 lambda 函数初始化静态数据成员
- 如何从 std::integer_sequence 初始化静态数组?
- 在构造函数中初始化静态函数指针
- C - 初始化静态成员的方法
- 大括号使用枚举类初始化静态常量unordered_map
- C++ main 函数中初始化静态变量
- 在定义(.cpp文件)中初始化静态浮点 constexpr 成员是可能的
- 错误 C2864:'element::next':只能在类 (STRUCT) 中初始化静态常量整数数据成员
- 我应该使用类内发起器初始化静态常量数据成员还是在其类外的定义中初始化静态常量数据成员
- 如何在运行时使用静态成员函数初始化静态成员变量
- 与其他静态const成员初始化静态常量成员