简体   繁体   English

表达式在c ++中必须具有恒定值

[英]expression must have a constant value in c++

So, I am creating an object that have an array as it's instance. 因此,我正在创建一个具有数组作为其实例的对象。 The size of this array will determined by the client program. 该数组的大小将由客户端程序确定。 Later in my program, I have to create a temp array that have the same capacity as the instance variable. 在程序的后面,我必须创建一个与实例变量具有相同容量的临时数组。 So, I put: 所以,我把:

int temp[capacity];

However, when I try to compile it, it failed. 但是,当我尝试编译它时,它失败了。 It said that I have to have a fix value instead of putting capacity. 它说我必须有一个固定值,而不是投入能力。 Any idea how can I fix this problem? 知道如何解决此问题吗? thx 谢谢

You can only construct such an array if capacity is known at compile time. 如果在编译时已知capacity则只能构造这样的数组。 For dynamically sized arrays, use std::vector : 对于动态大小的数组,请使用std::vector

#include <vector>

std::vector<int> temp(capacity); // makes a vector with capacity elements

Instead of writing this: 而不是这样写:

int temp[capacity]

Just write: 写吧:

int* temp = (int*)malloc(capacity);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM