动态初始化对象

发布于 2024-08-28 02:41:13 字数 581 浏览 8 评论 0原文

我有一个名为“玩家”的向量和一个名为“玩家”的类。我想做的是写:

players.push_back(Player(name, Weapon(bullets)));

所以我希望能够在循环中创建玩家。但我看到一条错误消息说“没有匹配的函数来调用 Player::Player...”

然后我将其更改为:

Weapon w(bullets);
Player p(name, w);
players.push_back(p);

这是我的 Player 定义:

class Player {
public:
   Player(string &name, Weapon &weapon);
private
   string name;
   Weapon weapon;
}

我只是想了解这些定义之间的区别。这是将对象传递给对象构造函数的正确方法吗?

注意:这些不是我实际的类定义。我只是想通过编写代码来学习一些有关 C++ 中面向对象编程的知识。我的意思是我知道武器可以在 Player 中初始化:)

I have a vector called players and a class called Player. And what I'm trying to do is to write:

players.push_back(Player(name, Weapon(bullets)));

So I want to be able to create players in a loop. But I see an error message says "no matching function for call Player::Player..."

Then I've changed that to:

Weapon w(bullets);
Player p(name, w);
players.push_back(p);

Here is my Player definition:

class Player {
public:
   Player(string &name, Weapon &weapon);
private
   string name;
   Weapon weapon;
}

I'm just trying to learn what is the difference between these definitions. And is this the right way to pass an object to an object constructor.

Note: These are not my actual class definitions. I'm just trying to learn something about object oriented programming in C++ with coding it. I mean I know that Weapon can be initialized in Player :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

入画浅相思 2024-09-04 02:41:13

将构造函数更改为:

Player(const string &name, const Weapon &weapon);

或:

Player(const string &name, Weapon weapon);

使用临时对象初始化引用是无效的 C++,而这正是您在使用时所做的事情:

Player(name, Weapon(bullets));

不过,使用 const 引用是合法的。

编辑:您还应该将名称作为const引用或按值传递。

Change constructor to:

Player(const string &name, const Weapon &weapon);

or:

Player(const string &name, Weapon weapon);

It's not valid C++ to initialize a reference with a temporary object, which is what you're doing when you use:

Player(name, Weapon(bullets));

it's legal to use a const reference though.

EDIT: You should also pass name as a const reference or by value.

蘸点软妹酱 2024-09-04 02:41:13

您将一个临时 (Weapon(bullets)) 传递给 Player 构造函数,该构造函数采用 Weapon &。但由于不允许您引用临时对象,因此此操作会失败。

但是,您可以对临时对象进行常量引用。因此,重新声明您的构造函数,如下所示:

   Player(string const &name, Weapon const &weapon);

You are passing a temporary (Weapon(bullets)) to the Player constructor, which takes a Weapon &. But since you're not allowed to make a reference to a temporary, this fails.

You are, however, allowed to make a const reference to a temporary. Thus, redeclare your constructor as follows:

   Player(string const &name, Weapon const &weapon);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文