动态初始化对象
我有一个名为“玩家”的向量和一个名为“玩家”的类。我想做的是写:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将构造函数更改为:
或:
使用临时对象初始化引用是无效的 C++,而这正是您在使用时所做的事情:
不过,使用
const
引用是合法的。编辑:您还应该将名称作为
const
引用或按值传递。Change constructor to:
or:
It's not valid C++ to initialize a reference with a temporary object, which is what you're doing when you use:
it's legal to use a
const
reference though.EDIT: You should also pass name as a
const
reference or by value.您将一个临时 (
Weapon(bullets)
) 传递给Player
构造函数,该构造函数采用Weapon &
。但由于不允许您引用临时对象,因此此操作会失败。但是,您可以对临时对象进行常量引用。因此,重新声明您的构造函数,如下所示:
You are passing a temporary (
Weapon(bullets)
) to thePlayer
constructor, which takes aWeapon &
. 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: