2016-03-18 28 views
0

我嘗試過的Google搜索引導我找到程序中有錯誤的人。我寧願知道如何正確執行,而不是從錯誤的代碼中回溯。在C++中,我該如何聲明一個將被類使用的數組?

我有一個數組,它是const int。

在我的課上,我想初始化一個不同的數組,但具有相同數量的元素。

初始化第一陣列之後,在I類已經試過:

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. :-(
); 

編譯器是幸福的,現在它有一個常量表達式,但我並不高興,因爲如果我將主體字符串的定義更改爲「更多字符」,則由我來手工計算出它們,或者使用.length()對它們進行計數,然後使用新常量數學表達式,全部手工完成。這看起來很容易發生。

因此,如果我有一個

const string thestring = "Dummy example"; 

如何然後聲明,在一個類中,相同長度的另一數組類內的虛設?

回答

0

您可以使用動態分配;

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(); 
+0

如果你不想/可以使用動態分配的,在C++ 11有可能用些辦法'constexpr '但我不確定。 – xvan

+0

我給了它一個嘗試,但'std :: basic_string '不是一個文字類型。因此,我們不能:使用'constexpr std :: string's,在'constexpr'函數中使用'std :: basic_string :: operator []'或'size()',或者使用'c_str )''constexpr'函數中獲取底層的C字符串並從那裏檢查長度。它也似乎ol''sizeof(x)/ sizeof(x [0])'成語不起作用;當與他的字符串一起使用時,它的計算結果是「32」而不是「13」。有可能有辦法做到這一點,但我還沒有足夠的技巧來弄清楚它是什麼。 –

+0

如果他使用的是C字符串,那很容易;正如N4121號文件中提出的那樣,'string_literal'也會有所幫助,但是我不知道發生了什麼,如果有的話。目前,我能想到的最好的事情就是編寫一個編譯時字符串類,比如'literal_str'(https://www.daniweb。com/programming/software-development/code/482276/c-11-compile-time-string-concatenation-with-constexpr),並給它一個'constexpr size_t size()'函數。如果需要,他還需要使用'std :: string'來創建一個方法。我真的不知道如何使用'constexpr'來獲得大小。 –

相關問題