【问题标题】:how to assign an array as another array within a class function如何在类函数中将数组分配为另一个数组
【发布时间】:2016-06-19 18:06:11
【问题描述】:
这基本上就是我想要做的:
class Player
{
public:
void setInventory(string inventory[]) { this->inventory = inventory; }
private:
string inventory[4];
};
通常我会使用strncpy();,但遗憾的是使用参数inventory[] 作为源不起作用,因为它不是const char *。如果可能的话,我想在一两行中将其保留为类内函数。我只想知道是否有一种简短的方法可以做到这一点,而不是在类之外为其创建一个函数。谢谢
【问题讨论】:
标签:
c++
arrays
function
class
【解决方案1】:
std::copy 如果你想要数组元素的副本,或者std::move 如果你被允许从它们移动。
例子:
class Player
{
public:
void setInventory(std::string inventory[]) {
std::copy(inventory, inventory + 4, this->inventory);
}
private:
std::string inventory[4];
};
请注意,您应该确保您的“数组参数”(实际上是一个指针)应该(至少)具有所需的 4 个元素。如果可能,最好将大小编码为类型,例如使用std::array。
struct Player {
void setInventory(std::array<std::string, 4> i) {
inventory = i;
}
std::array<std::string, 4> inventory;
};
这是因为std::array 实现了赋值运算符operator=。
【解决方案2】:
您不会使用stdncpy(),inventory 是std::string 的数组,而不是char。
你可以写一个简单的循环来做到这一点,
void setInventory(string inventory[]) {
for (int i = 0; i < 4; i++)
this->inventory[i] = inventory[i];
}
但最简单的方法是使用std::array。
class Player
{
public:
void setInventory(const std::array<std::string, 4>& inventory) { this->inventory = inventory; }
private:
std::array<std::string, 4> inventory;
};
【解决方案3】:
你真的应该把你的库存存储变成一个类型或类本身,这样你就可以统一和清晰地对待它。这将自动让您复制/移动操作(假设最近的标准兼容编译器)以保持处理清晰:
typedef std::array<std::string, 4> Inventory;
class Player
{
public:
void setInventory(Inventory &&inventory) {
this->inventory = inventory;
}
private:
Inventory inventory;
};
这样做还允许您在将来扩展和增强 Inventory 本身,对从外部处理它的代码进行零或最少的重构。