2016-07-03 36 views
-3

我有一個類Screen其成員內容使用std::string(size_t, char)構造函數初始化。不能使用字符串(size_t,char)的構造函數

#include <iostream> 
#include <string> 

struct Screen { 
    friend std::ostream& print(std::ostream& os ,const Screen& screen); 

    Screen() = default; 
    Screen(std::size_t w, std::size_t h) : 
    width(w), height(h), content(w * h , ' ') {} 

    Screen(std::size_t w, std::size_t h, char c) : 
    width(w), height(h), content(w * h, c) {} 

private: 
    std::size_t width = 24; 
    std::size_t height = 80; 
    std::size_t cursor = 0; 
    std::string content(width * height, ' '); 
}; 

我想宣佈在主裏面類似的方式爲字符串,但我得到了同樣的錯誤,我無法弄清楚我在做什麼錯在這裏。

structures.cpp:15:25: error: 'width' is not a type 
    std::string content(width * height , ' '); 
         ^
structures.cpp:15:42: error: expected identifier before '\x20' 
    std::string content(width * height , ' '); 
             ^
structures.cpp:15:42: error: expected ',' or '...' before '\x20' 
+0

爲什麼不使用初始化列表來構造'std :: string'?它試圖初始化你在哪裏聲明你的字符串的目的是什麼?'string content((width * height),'');'? – PaulMcKenzie

回答

2

以下內容修復了您的代碼。我想需要一個成員函數聲明和成員數據定義之間的一個小歧義:

std::string content = std::string(width * height, ' '); 

但我會做的,而不是在構造函數中重複自己是用委託構造函數和默認參數:

struct Screen 
{ 
    Screen(std::size_t w, std::size_t h, char c = ' ') : 
    width(w), 
    height(h), 
    content(w * h, c) 
    {} 

    Screen() : 
    Screen(24, 80) 
    {} 

private: 
    std::size_t width; 
    std::size_t height; 
    std::string content; 
}; 

你就完成了。

1

我從來沒有使用這種語法,但它似乎可以初始化類體中的std :: string如下:

std::size_t width = 24; 
std::size_t height = 80; 
std::size_t cursor = 0; 
std::string content{std::string((width * height), ' ')}; 

你應該記得要保持初始化按以上順序。

你的代碼存在的問題是,如果你在構造函數的初始化列表中初始化了content,那麼編譯器將不會執行初始化,這是你的變量定義。所以 - 正如你在一個評論中所說 - 你不能進行默認初始化,然後在構造函數中覆蓋它。

相關問題