我在C++中有以下类:
class a {
const int b[2];
// other stuff follows
// and here's the constructor
a(void);
}
Run Code Online (Sandbox Code Playgroud)
问题是,如何在初始化列表中初始化b,因为我无法在构造函数体内初始化它,因为b是const?
这不起作用:
a::a(void) :
b([2,3])
{
// other initialization stuff
}
Run Code Online (Sandbox Code Playgroud)
编辑:这个例子就是我可以b为不同的实例设置不同的值,但是已知这些值在实例的生命周期内是不变的.
有没有人有办法初始化一个ints 数组(任何多字节类型真的很好),简单到一个非零和非-1值?我的意思是,有没有办法在单个班轮中执行此操作,而无需单独执行每个元素:
int arr[30] = {1, 1, 1, 1, ...}; // that works, but takes too long to type
int arr[30] = {1}; // nope, that gives 1, 0, 0, 0, ...
int arr[30];
memset(arr, 1, sizeof(arr)); // That doesn't work correctly for arrays with multi-byte
// types such as int
Run Code Online (Sandbox Code Playgroud)
仅供参考,memset()在静态数组上使用这种方式可以得到:
arr[0] = 0x01010101
arr[1] = 0x01010101
arr[2] = 0x01010101
Run Code Online (Sandbox Code Playgroud)
另一种选择:
for(count = 0; count < 30; count++)
arr[count] = 1; // Yup, that does …Run Code Online (Sandbox Code Playgroud) 我在 C 中有以下代码可以正常工作
typedef struct { float m[16]; } matrix;
matrix getProjectionMatrix(int w, int h)
{
float fov_y = 1;
float tanFov = tanf( fov_y * 0.5f );
float aspect = (float)w / (float)h;
float near = 1.0f;
float far = 1000.0f;
return (matrix) { .m = {
[0] = 1.0f / (aspect * tanFov ),
[5] = 1.0f / tanFov,
[10] = -1.f,
[11] = -1.0f,
[14] = -(2.0f * near)
}};
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在 C++ 中使用它时,我收到此编译器错误:
error C2143: syntax …