我正在尝试使用setter函数将一个Object添加到矢量。我的文件如下
#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'没有已知的转换。传递&amp; newUser表示从“用户**”到“用户”的参数1没有已知的转换。我需要改变我的载体,还是有其他方法可以做到这一点?
答案 0 :(得分:3)
我怀疑你是来自Java。在C ++中,typename表示值,而不是引用,您不需要使用new
来分配对象:
User newUser(myUsername, myPassword); // creates a User
Room newRoom; // creates a Room
newRoom.addToRoom(newUser);
答案 1 :(得分:0)
您将用户指针与用户本身混淆。您的addToRoom函数具有void()(User)的签名,但您使用签名void()(User *)调用它。
在您的特定示例中,也没有任何理由使用new分配内存。您只需在堆栈上创建对象即可完成所有操作。