数组的 C++ 类构造函数
c++ class constructor for array
我正在写一个Matrix2D
类。一开始我使用构造函数作为 folows,
我的代码:
Matrix2D(float a,float b, float c,float d)
{
a_=a;
....
}
但是,我刚刚意识到,如果我可以使用多维array [2][2]
,那就更好了。这就是问题所在,如何为数组编写构造函数?
class Matrix
{
float matrix[2][2];
public:
Matrix2D(float a,float b,float c, float d)
{
matrix[2][2]={a,b,c,d} // not valid
}
}
只是为了让你知道,我不要求完整的代码。我只需要有人让我走上正轨。
对于 C++11,您可以执行以下操作:
Matrix(float a,float b,float c, float d) :
matrix{{a,b},{c,d}}
{
}
C++03没有干净的替代品。
matrix[0][0] = a; // initialize one element
等等。
矩阵[0][0] = 你想要的值 矩阵 [n][n] = 你想要的值,但在循环中计数因此,矩阵的大小可以是动态的,也可以稍后重用代码。
for(int ii(0); ii < first dimension size; ++ii)
{
for(int ll(0); ii < second dimension size; ++ll)
{
matrix[ii][ll] = value you want;
}
}
这将使您的代码在此应用程序之外更具可扩展性和更有用性,并且可能没有用,或者可能有用。
如果它是一个矩阵 2X2,那么你可以传递一个浮点数组,然后循环遍历它。
例如
for(int x = 0;x<4;x++)
{
matrix[0][x] = myarray[x];
}
如果你有一个C++11编译器,Luchian的版本是最好的。 这是一个适用于所有版本的C++:
struct matrix_holder { float matrix[2][2]; };
class Matrix : matrix_holder
{
static matrix_holder pack(float a,float b,float c, float d)
{
matrix_holder h = { {{a, b}, {c, d}} };
return h;
}
public:
Matrix(float a,float b,float c, float d) : matrix_holder(pack(a,b,c,d))
{
}
};
优化程序将内联帮助程序。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为