【问题标题】:How to reference functions from other classes to add value to vector如何引用其他类的函数为向量添加值
【发布时间】:2018-09-19 06:10:34
【问题描述】:

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

#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 没有从“用户*”到“用户”的已知转换。传递 &newUser 表示参数 1 没有从“用户**”到“用户”的已知转换。我需要改变我的载体,还是有其他方法可以做到这一点?

【问题讨论】:

  • 你可以直接使用User newUser(myUsername, mypassword) 而不是使用new。
  • 顺便说一句,addUser(User user) 是比 addToRoom(User user) 更好的函数名称。
  • 您可能希望通过引用传递User 以防止制作不必要的临时副本。

标签: c++ class vector iterator


【解决方案1】:

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

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

【讨论】:

  • 或 C++11 中的 newRoom.addToRoom(std::move(newUser));
  • @DanielLangr 代码在最小化副本方面还有很多不足之处。 newRoom.addToRoom({myUsername, myPassword}); 也同样有效
  • 我喜欢 Ryan 的做法。
【解决方案2】:

您将指向用户的指针与用户本身混淆了。您的 addToRoom 函数的签名为 void()(User),但您使用签名 void()(User*) 调用它。

在您的特定示例中,也没有任何理由使用 new 分配内存。您只需在堆栈上创建对象即可完成所有工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    相关资源
    最近更新 更多