首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用另一个静态成员声明静态成员数组维度

使用另一个静态成员声明静态成员数组维度
EN

Stack Overflow用户
提问于 2022-10-17 04:33:19
回答 1查看 39关注 0票数 -1

Apple编译器(版本clang-1400.0.29.102)允许使用另一个静态成员声明静态成员数组维度,但在UbuntuUbuntu编译器(Version11.2.0-19ubuntu1)中不允许使用。在声明时,编译器似乎假设变量strings的维度中使用的变量的值为1,但试图在定义时对它们进行评估。

是否有办法让Ubuntu编译器“等待”而不声明strings,直到定义了其维度中使用的变量?

代码语言:javascript
复制
class MyClass
{
    // declarations
    static const int i_num_strs;
    static const int i_str_lens;
    static const char strings[i_num_strs][i_str_lens];
};

// defintions
const int MyClass::i_num_strs = 5;
const int MyClass::i_str_lens = 6;
const char MyClass::strings[i_num_strs][i_str_lens] = 
{
    "one",
    "two",
    "three",
    "four",
    "five"
}

在MacOS上编译时没有问题,但是在Ubuntu上编译时会出现以下“冲突声明”错误:

代码语言:javascript
复制
test_test.cpp:8:43: error: size of array ‘strings’ is not an integral constant-expression
    8 |     static const char strings[i_num_strs][i_str_lens];
      |                                           ^~~~~~~~~~
test_test.cpp:8:31: error: size of array ‘strings’ is not an integral constant-expression
    8 |     static const char strings[i_num_strs][i_str_lens];
      |                               ^~~~~~~~~~
test_test.cpp:14:41: error: size of array ‘strings’ is not an integral constant-expression
   14 | const char MyClass::strings[i_num_strs][i_str_lens] =
      |                                         ^~~~~~~~~~
test_test.cpp:14:29: error: size of array ‘strings’ is not an integral constant-expression
   14 | const char MyClass::strings[i_num_strs][i_str_lens] =
      |                             ^~~~~~~~~~
test_test.cpp:21:1: error: too many initializers for ‘const char [1][1]’
   21 | };
      | ^

免责声明:--这是一个不需要动态内存分配且不允许宏的应用程序。

EN

回答 1

Stack Overflow用户

发布于 2022-10-17 04:40:44

停止使用"C“样式数组(特别是字符串),这是C++。您可以使用constexpr + string_view来定义在编译时为常量的字符串。

代码语言:javascript
复制
#include <array>
#include <string_view>
#include <iostream>

class MyClass
{
public:
    static constexpr std::array<std::string_view, 5> strings
    { 
        "One","Two","Three","Four","Five" 
    };
};


int main()
{
    std::cout << MyClass::strings[2] << "\n\n";

    for (const auto& value : MyClass::strings)
    {
        std::cout << value << "\n";
    }

    return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74092613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档