我当时正在 Linux 上的 Netbeans 中使用 gcc 编译器编写一个程序,当切换到 Windows 7 上的 Visual C++ 时,代码无法编译,因为 Visual C++ 表示它在几行中需要常量表达式
。在 Netbeans 上,我只是做了类似于 char name[fullName.size()]; 的操作,而在 Visual C++ 上,我尝试了除其他外,
const int position = fullName.size();
char Name[position];
如何创建用于数组的常量?
注意:我知道这个问题,但是有什么方法可以让我在不使用的情况下完成这个工作向量,因为这需要重写程序的许多部分?
I was working on a program in Netbeans on Linux using a gcc compiler when, upon switching to Visual C++ on Windows 7, the code failed to compile as Visual C++ says it expected constant expression
on several lines. On Netbeans, I simply did something similar to char name[fullName.size()];
, while on Visual C++, I tried, among other things,
const int position = fullName.size();
char Name[position];
How can I create a constant to use for the array?
Note: I know about this question, but is there any way I can get this working without using vectors, since that would require a re-write of many parts of the program?
发布评论
评论(4)
这在 VC++ 中是不可能的。我知道,非常悲伤 :(
解决方案包括:
新的 C++ 标准 (C++0x) 提出了一个“常量表达式”功能来处理这个问题。有关详细信息,请检查 这个了。
This is not possible in VC++. I know, pretty sad :(
The solutions include:
The new C++ standard (C++0x) proposes a 'constant expression' feature to deal with this. For more info, check this out.
在 VC++ 中,您无法执行堆栈数组大小的运行时声明,但您可以通过 _alloca
所以这个:
变成这样:
这不是完全相同的事情,但它与你在 VC++ 中得到的最接近。
In VC++ you can't do runtime declarations of stack array sizes, but you can do stack allocation via _alloca
so this:
becomes this:
It's not quite the same thing, but it's as close as you are going to get in VC++.
C++ 要求在编译时知道数组的大小。如果您不介意使用非标准扩展,gcc 确实允许像您所做的那样的代码(请注意,虽然它不是标准 C++,但从 C99 开始,它是 C 中的标准)。
我还猜测您可以使用向量(在这个特定的地方),而且比您想象的要少一些麻烦——为数组编写的相当多的代码只需重新编译即可使用向量,并且很少或者根本不重写。
C++ requires that the size of the array be known at compile time. If you don't mind using a non-standard extension, gcc does allow code like you're doing (note that while it's not standard C++, it is standard in C, as of C99).
I'd also guess that you could use a vector (in this particular place) with less trouble than you believe though -- quite a bit of code that's written for an array can work with a vector with only a re-compile, and little or no rewriting at all.
您的
char name[fullName.size()];
是 可变长度数组 - 据我所知 - 在 C++ 中没有标准化,所以你只能受编译器的摆布。[稍微偏离主题,它们是 C99 标准的一部分]
Your
char name[fullName.size()];
is an example of a variable-length array which - as far as I know - are not standardized in C++ so you're at the mercy of the compiler.[Slightly off-topic they're part of the C99 standard]