c++ - 无法初始化 vector C++

标签 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 的 vector 。 提前致谢

最佳答案

使用成员初始化列表,在构造函数的定义中为:

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!
  }
};

关于c++ - 无法初始化 vector C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6422371/

相关文章:

c++ - 从另一个文件引用 C++ 类

c++ - “numeric_limits”不是模板

c++ - 在调用实际析构函数之前删除了字段变量?

c++ - OpenGL:wglGetProcAddress 总是返回 NULL

c++ - 为什么我的 removestring 函数有错误

c++ - 如何为多个文件处理选择最佳 I/O 策略?

c++ - 在派生类中使用 protected 说明符

c++ - 从主循环调用守护进程函数?

c++ - 无法在opencv中读取视频

c# - MarshalAs(UnmanagedType.ByValArray, SizeConst 大小限制