Visual C ++表达式必须具有恒定值 [英] Visual C++ Expression must have a constant value

查看:65
本文介绍了Visual C ++表达式必须具有恒定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道为什么Visual Studio是唯一给我这个错误的编译器-表达式必须具有恒定值(指大小).

Does anyone know why Visual Studio is the only compiler to giving me this error - Expression must have a constant value (referring to size).

#include <iostream>
#include <cstring>
using std::cout; using std::endl;

int main() {
    const char Ca3[] = { "Hello" };
    const char Ca4[] = { "World" };

    const size_t size = strlen(Ca3) + strlen(Ca4) + 2;

    char bigString[size];
    strcpy(bigString, Ca3);
    strcat(bigString, " ");
    strcat(bigString, Ca4);
    cout << bigString << endl;

    system("PAUSE");
    return 0;
}

推荐答案

strlen 函数未声明为 constexpr ,这意味着它的结果不是恒定表达.

The strlen function is not declared as constexpr, which means that the result of it is not a constant expression.

因此 size 不是常量表达式,因此不能用作数组维.该代码在标准C ++中格式错误.

So size is not a constant expression and therefore it cannot be used as an array dimension. The code is ill-formed in Standard C++.

许多编译器都有一个扩展,可以将非恒定表达式用作数组维.如果另一个编译器接受此代码,则可能是解释原因.您也许可以使用符合标准的开关(例如,用于gcc, -std = c ++ 14 -pedantic )来生产其他编译器.

Many compilers have an extension that non-constant expressions may be used as an array dimension. If another compiler accepts this code then that would probably be the explanation. You might be able to prod the other compilers by using standards-compliance switches (e.g. for gcc, -std=c++14 -pedantic).

要解决此问题,您可以编写自己的 constexpr 等效于 strlen ;或者您可以使用 sizeof .或者,您可以使用 std :: string 并完全避免使用C样式的字符串.

To work around this you could write your own constexpr equivalent to strlen; or you could use sizeof. Alternatively you could use std::string and avoid C-style string handling entirely.

这篇关于Visual C ++表达式必须具有恒定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆