2 wangrand wangrand 于 2015.06.08 11:34 提问

C++primer 关于容器中的类的初始化

头文件Header.h:

 #ifndef FUNC
#define FUNC
#include<string>
#include<vector>
using namespace std;
class Screen;
class Window_mgr
{
public:
    friend class Screen;
    typedef vector<Screen>::size_type ScreenIndex;
    Window_mgr() = default;
    ScreenIndex addScreen(const Screen&);
    void clear(ScreenIndex);
private:
    vector<Screen> screens{Screen(24,80,' ')};
};
class Screen
{
    friend void Window_mgr::clear(ScreenIndex);
public: 
    typedef string::size_type pos;
    Screen() = default;
    Screen(pos ht, pos wd) :height(ht), width(wd){ contents = string(ht*wd, ' '); }
    Screen(pos ht, pos wd, char c) :height(ht), width(wd), contents(ht*wd, c){}
    char get()const { return contents[cursor]; cout << cursor << height << width; }
    inline char get(pos ht, pos wd)const;
    Screen &move(pos r, pos c){ cursor = r*width + c; return *this; }
    Screen &set(char c){ contents[cursor] = c; return *this; }
    inline Screen& display(ostream &);

private:
    pos cursor = 0;
    pos height = 0, width = 0;
    string contents;
};
inline
    Screen& Screen::display(ostream &co)
{
        co << contents;
        return *this;
    }
Window_mgr::ScreenIndex
Window_mgr::addScreen(const Screen&s)
{
    screens.push_back(s);
    return screens.size()-1;
}
void Window_mgr::clear(ScreenIndex i)
{
    Screen &s = screens[i];
    s.contents = string(s.height*s.width, ' ');
}
#endif

源文件source.cpp:

 #include<iostream>
#include"Header.h"
int main()
{
    Window_mgr ms;
    Screen myScreen(5, 5, 'X');
    myScreen.move(4, 0).set('#').display(cout);
    cout << "\n";
    myScreen.display(cout);
    cout << "\n";
    return 0;   
}

VS2013编译器提示 :
Error 1 error C2514: 'Screen' : class has no constructors c:\users\orgrand.w\documents\visual studio 2013\projects\demo\header.h 16 1 Demo

Error 2 error C1903: unable to recover from previous error(s); stopping compilation c:\users\orgrand.w\documents\visual studio 2013\projects\demo\header.h 16 1 Demo

光标指向这条语句: vector screens{Screen(24,80,' ')};
怎么修改才能实现这个初始化呢?

3个回答

liqiongfan
liqiongfan   2015.06.08 13:08

vector screens{Screen(24, 80, '')};这行是错误的哈。

vector的初始化只能是如下的几种:
1. vector v1;
2. vector v2(v1);
3. vector v3(n, i);
4. vector v4(n);
并没有使用vector Name{};的初始化形式,数组是这样初始化,但是容器不是这样初始化的。如:
数组初始化:
int a[] = {1,2,3,4};
容器初始化:
vector v1();而且不允许对容器使用vector v1 = {};的形式。


monaso
monaso   2015.06.08 16:03

把这句vector screens{Screen(24,80,' ')}换成vector screens(Screen(24,80,' '))试试。

oyljerry
oyljerry   Ds   Rxr 2015.06.08 22:00

你这个需要支持in class initialization。需要支持c++11的编译器

Csdn user default icon
上传中...
上传图片
插入图片