如何创建动态分配的const对象数组,但要为其赋值
How to create a dynamically-allocated array of const objects, but have values assigned to them?
我需要创建一个动态分配的const对象数组。困难的是,我还需要给const对象赋值。
我需要这个SFML类的Samples变量
我该怎么做?
您不需要const
对象的数组。指向const的指针既可以指向const对象,也可以指向非const对象;你可以创建一个动态数组,并从它初始化一个Chunk
结构,像这样:
std::vector<Int16> samples;
initialise(samples);
// valid until 'samples' is destroyed or resized
SoundStream::Chunk chunk = {&samples[0], samples.size()};
Easy:
// Step 1: Make an array of const values:
const int arr[] = { 1, 4, 9, 17 };
// Step 2: Make a pointer to it:
auto parr = &arr; // 2011-style
const int (*pbrr)[4] = &arr; // old-style
你不能给常量"赋值"(显然),所以给常量赋值的唯一方法是初始化为该值。
或者,如果在编译时不知道数据:
const std::vector<int> function() {
std::vector<int> tmp(5); //make the array
for(int i=0; i<5; ++i)
tmp [i] = i; //fill the array
return tmp;
}
进行分配,将其赋值给指向非const的指针。对数据进行修改。当你做了这些乱七八糟的事情之后,你可以把const指针赋值给数组。例如:
int * p = new int[100];
for (int i=0; i<100; ++i)
p[i] = i;
const int * cp = p;
如果需要动态分配数组,我建议使用标准容器:
std::vector<Int16> data;
Chunk* c = ...;
data.push_back(...);
c->Samples = &data[0];
相关文章:
- 在 Arduino 中为 2D 指针数组赋值
- 我无法为 2D 数组赋值
- 如何在C++中初始化值,然后稍后为uint32_t数组赋值
- 使用 C++ shell 为 C++ 中的 2 D 动态数组赋值,控制台不会打印出任何内容
- 为两个动态数组赋值
- 在类的构造函数中为常量动态大小的数组赋值
- 为结构灵活数组赋值
- 如何在opencv中为三维数组赋值
- 如何从主函数为对象数组赋值
- 数组赋值无法使用指针语法
- C++类中的静态数组赋值
- 多维字符串数组赋值 C++
- 错误:从初始值设定项列表向数组赋值;在ubuntu 1004上工作但在14.04上不工作的代码
- 用于循环数组赋值的C++.正在返回垃圾邮件
- 多维数组赋值
- 无法在c++中为全局数组赋值
- C++程序在为指针的2D数组赋值后崩溃
- 给指针数组赋值
- c++将整型数组赋值给大小相同的空整型数组
- 将数组赋值给派生对象