无法初始化向量C ++

时间:2011-06-21 08:26:30

标签: c++

SockeClient.h文件

#define SIZE_OF_BUFFER 4096

class SocketClient {

public:
    SocketClient(int cfd);
    virtual ~SocketClient();

    int recv();
    int getFd();

protected:
    int             m_fd;
    char            *m_buffer;
    vector<char>    m_vbuffer;

};

我正在尝试

vector<char>    m_vbuffer(SIZE_OF_BUFFER);

我遇到语法错误...如何初始化大小为4096的向量。 提前致谢

3 个答案:

答案 0 :(得分:3)

使用member-initialization-list,在构造函数的定义中为:

class SocketClient {

public:
    SocketClient(int cfd) : m_vbuffer(SIZE_OF_BUFFER) 
    {                   //^^^^^^^^^^^^^^^^^^^^^^^^^^^ member-initialization-list

         //other code... 
    }


protected:
    int             m_fd;
    char            *m_buffer;
    vector<char>    m_vbuffer;

};

您可以使用member-initialization-list将许多成员初始化为:

class A
{
  std::string s;
  int a;
  int *p;
  A(int x) : s("somestring"), a(x), p(new int[100])
  {
    //other code if any
  }
 ~A()
  {
     delete []p; //must deallocate the memory!
  }
};

答案 1 :(得分:1)

在SocketClient的构造函数中调用m_vbuffer-&gt; reserve(SIZE_OF_BUFFER)。

答案 2 :(得分:0)

除了其他答案之外,请考虑使用一些circular buffer而不是矢量。 boost中有一个。