我正在尝试使用 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/