简体   繁体   中英

How to reference functions from other classes to add value to vector

I'm trying to add an Object to a vector using a setter function. My files are as follows

#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 is just

users.push_back(user);

My user.h is

#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

I am trying to do

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;

}

However, if I pass in newUser, I get an error saying there is no matching function, there is no known conversion for argument 1 from 'User*' to 'User'. Passing &newUser says that there is no known conversion for argument 1 from 'User**' to 'User'. Do I need to alter my vectors, or is there another way to do this?

I suspect you are coming from Java. In C++, a typename indicates a value, not a reference, and you don't need to use new to allocate an object:

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

You are confusing a pointer to a User with the User itself. Your addToRoom function has a signature of void( )(User), but you're calling it with the signature void( )(User*).

In your particular example, there also isn't any reason to allocate memory with new. You can do everything by just creating objects on the stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM