【问题标题】:In C++ how do I declare an array which will be used by a class?在 C++ 中,如何声明一个类将使用的数组?
【发布时间】:2016-03-18 18:36:16
【问题描述】:

我尝试过的 Google 搜索将我引导到程序中存在错误的人。我宁愿只知道如何正确地做到这一点,也不愿从错误的代码中回溯。

我有一个数组,它是 const int。

在我的班级中,我想用相同数量的元素初始化一个不同的数组。

初始化第一个数组后,在我尝试过的类中:

int array[array.length()];

但是编译器抱怨它不是一个常量表达式。

即使我

const string thestring = "Dummy example";
const static int strlen = (int)thestring.length();

然后在第一节课:

class dostuff {
    int newstring[strlen];
);

编译器还在抱怨我。

这让我先尝试做声明,例如:

const string thestring = "Dummy";

然后在类中,手工统计元素即可:

class Enigmatise {
    int duplicatelengthstring[5]; // Just counted by hand. :-(
);

编译器现在很高兴它有一个常量表达式,但我不高兴,因为如果我将原则字符串的定义更改为“更多字符”,那么就由我来手动计算它们,或者 cout使用 .length(),然后在类中使用新的常量数值表达式,全部手动完成。这看起来很容易发生事故。

因此,如果我有一个

const string thestring = "Dummy example";

然后我如何在一个类中声明另一个与类中的 dummy 长度相等的数组?

【问题讨论】:

    标签: arrays string class declaration


    【解决方案1】:

    您可以使用动态分配;

    class anotherclass {
            const std::string thestring;
            int * const otherArray;
    
            anotherclass() : thestring("some string"),
                             otherArray(new int[(int)thestring.length()]){}
            ~anotherclass(){delete[] otherArray;}
       };
    

    编辑:编译时没有警告

    class anotherclass {        
        static const std::string thestring;
        static const int strlen;
        public:
        void dosomething( ){int g[strlen]; }
    };
    
    
    const std::string anotherclass::thestring = "mystring";
    const int anotherclass::strlen = anotherclass::thestring.length();
    

    【讨论】:

    • 如果你不想/不能使用动态分配,在 C++11 下可能可以使用constexpr 解决问题,但我不确定。
    • 我试了一下,但std::basic_string<T> 不是文字类型。因此,我们不能:制作constexpr std::strings,在constexpr 函数中使用std::basic_string<T>::operator[]size(),或者在constexpr 函数中使用c_str() 来获取底层C 字符串并检查从那里开始的长度。似乎 ol' sizeof(x) / sizeof(x[0]) 成语也行不通;当与他的字符串一起使用时,它的计算结果为32 而不是13。可能有办法做到这一点,但我还不够熟练,无法弄清楚它是什么。
    • 如果他用的是C字符串就很容易了; string_literal,正如论文 N4121 中所建议的那样,也会有所帮助,但我不知道发生了什么,如果有的话。目前,我能想到的最好的办法是制作一个编译时字符串类,例如literal_strdaniweb.com/programming/software-development/code/482276/…),并给它一个constexpr size_t size() 函数。如果需要,他还需要设法将其与std::string 一起使用。老实说,我不知道如何使用constexpr 来获取大小。
    猜你喜欢
    • 2020-02-15
    • 1970-01-01
    • 2020-03-02
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多