c++ - 如何引用其他类的函数来为 vector 添加值

标签 c++ class vector iterator

我正在尝试使用 setter 函数将对象添加到 vector 。我的文件如下

#ifndef ROOM_H
#define ROOM_H

#include <string>
#include <vector>
#include "User.h"
using namespace std;

class Room {
    vector<User> users;

public:
    Room();
    void addToRoom(User user);
    vector<User> getUsers();
};

#endif

addToRoom 只是

users.push_back(user);

我的user.h是

#ifndef USER_H
#define USER_H
#include <string>
#include <vector>

using namespace std;

class User {

        string password;
        string username;

public:
        User(string user, string pass);
        string getPass();
        string getName();
};

#endif

我正在努力

void
IRCServer::addUser(int fd, const char * user, const char * password, const char * args)
{

        string myUsername = user;
        string myPassword = password;
        User *newUser = new User(myUsername, myPassword);
        Room *newRoom = new Room();
        newRoom->addToRoom(newUser);


        return;

}

但是,如果我传入 newUser,我会收到一条错误消息,指出没有匹配的函数,参数 1 没有从“User*”到“User”的已知转换。传递 &newUser 表示参数 1 没有从“User**”到“User”的已知转换。我需要改变我的载体,还是有其他方法可以做到这一点?

最佳答案

我怀疑您来自 Java。在 C++ 中,typename 表示一个值,而不是一个引用,您不需要使用 new 来分配对象:

User newUser(myUsername, myPassword); // creates a User
Room newRoom;  // creates a Room
newRoom.addToRoom(newUser);

关于c++ - 如何引用其他类的函数来为 vector 添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49739809/

相关文章:

python - 为 tkinter 小部件创建一个类来调用默认属性

c++ - 在 C++ vector 的每个元素上调用函数

c++ - 巴达 C++ std::stringstream

C++ TCP套接字垃圾值

c++ - 任何人都可以演示 fl_filename_list 吗?

Javascript OOP/类 - 多个实例共享相同的数据

Java没有其他类的响应

c++ - 如何使用扩展的球形扇形(圆锥)来迭代坐标球?

r - 计算连续值之间的差异或与 R 中向量中最新的非 NA 值的差异

c++ - 返回 vector<auto_ptr<T>> 是否安全?