標籤:

按C++ Prime裡面說的寫類Screen和Windows_mgr出現下面的錯誤,求大神解答?

代碼如下:

#include&
#include&
#include&

class screen{
public:
using pos = std::string::size_type;
screen() = default;
screen(pos, pos);
screen(pos, pos, char);
screen move(pos, pos);
screen set(pos, pos, char);
screen set(char);
screen display(std::ostream);
const screen display(std::ostream) const;

private:
pos cursor = 0;
pos height = 0, width = 0;
std::string contents;
void do_display(std::ostream os) const{ os &<&< contents; } friend class windows_mgr; }; screen::screen(pos row, pos col) :height(row), width(col), contents(row*col, ){} screen::screen(pos row, pos col, char c) : height(row), width(col), contents(row*col, c){} screen screen::move(pos row, pos col){ cursor = row*width + col; return *this; } screen screen::set(char c){ contents[cursor] = c; return *this; } screen screen::set(pos row, pos col, char c){ contents[row*width + col] = c; return *this; } screen screen::display(std::ostream os){ do_display(os); return *this; } const screen screen::display(std::ostream os) const{ do_display(os); return *this; } class windows_mgr{ public: typedef std::vector&::size_type screenIndex;
void clear(screenIndex i);
private:
std::vector& vscreens{ screen(5, 5, X) };
};

void windows_mgr::clear(screenIndex i){
screen s = vscreens[i];
s.contents = std::string(s.height*s.width, );
}

在class windows_mgr中定義std::vector& vscreens{ screen(5, 5, X) }時出現如下error:

error C2664: 「std::vector&&>::vector(std::initializer_list&,const std::allocator&<_Ty&> )」: 無法將參數 1 從「screen」轉換為「const std::allocator&<_Ty&> 」

環境:vs2013

請問是什麼原因,希望有大神能給出解答


不知道是不是遇到了bug,你可以暫時寫成這樣:

class windows_mgr
{
public:
typedef std::vector&::size_type screenIndex;
void clear(screenIndex i);
private:
std::vector& vscreens;
public:
windows_mgr()
:vscreens({screen(5, 5, X)})
{
}
};


VS2015 update3、clang 3.8和gcc6.1.1均表示沒有任何編譯錯誤

升級下VS

啊看到輪子叔回答才想起來應該告訴題主怎麼規避的

這應該是VS2013的類內初始值初始化的bug,你可以手動把它寫進構造函數里,就像輪子叔那樣

(其實輪子叔在初始化列表那裡一對小括弧可以刪掉


順便補充個問題解決,如果做使用vs2013做課後那道題(練習7.32)當你使用成員函數clear作為Screen的友元時,會提示你無法訪問contents,不過程序是可以正常運行的······


clang 3.8沒問題,應該是VS2013的bug吧。。。


推薦閱讀:

Qt 為什麼在桌面應用(Windows 平台)中不流行呢?
如何用批處理對C語言程序進行批改?
微軟會把 clang 擴展到可以徹底替換 C1,並真的換掉 C1 嗎?
計算機專業C++應該怎麼教?
斷言、異常和返回值的選擇問題?

TAG:C | CPrimer |