如何向向量中添加“新”类 [英] How to add a 'new' class to a vector

查看:150
本文介绍了如何向向量中添加“新”类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中编写一个服务器,并创建了一个名为client的类来存储关于连接的客户端的信息。我想把客户端存储在一个向量中。我有一个调用

I am writing a server in C++ and created a class called client to store information about connected clients. I wanted to store the clients in a vector. I have a call

clients.push_back(new client(addr,fd));

向客户端添加客户端对象。我在编译时得到以下错误

to add a client object to the vector clients. I get the following error on compile

server.cpp:67: error: no matching function for call to ‘std::vector<client, std::allocator<client> >::push_back(client*)

我认为这与我对 new 关键字以及如何在C ++中存储/移动数据。我来自Java背景,所以我不使用C ++的指针和记忆的东西。

I think it has something to do with my misunderstanding of the new keyword and how data is stored/moved in C++. I come from a Java background, so I am not use to pointers and memmory stuff of C++.

推荐答案

删除,因此它是:

clients.push_back(client(addr, fd));

在Java中,你必须显式地 new all你的对象,但在C ++你不仅不需要,但一般想避免它时/如果一切合理。

In Java you have to explicitly new all your objects, but in C++ you not only don't need to, but generally want to avoid it when/if at all reasonable.

这篇关于如何向向量中添加“新”类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆