Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将数组指定为类函数中的另一个数组_C++_Arrays_Function_Class - Fatal编程技术网

C++ 如何将数组指定为类函数中的另一个数组

C++ 如何将数组指定为类函数中的另一个数组,c++,arrays,function,class,C++,Arrays,Function,Class,这基本上就是我要做的: class Player { public: void setInventory(string inventory[]) { this->inventory = inventory; } private: string inventory[4]; }; 通常我会使用strncpy()但遗憾的是,使用参数inventory[]作为源代码不起作用,因为它不是const char*。如果可能的话,我想把它作为一个类内函数保存在一两行中。我只是想知道是否有

这基本上就是我要做的:

class Player
{
public:
    void setInventory(string inventory[]) { this->inventory = inventory; }
private:
    string inventory[4];
};
通常我会使用
strncpy()
但遗憾的是,使用参数
inventory[]
作为源代码不起作用,因为它不是
const char*
。如果可能的话,我想把它作为一个类内函数保存在一两行中。我只是想知道是否有一种简单的方法来实现这一点,而不是在类之外为它创建一个函数。谢谢

如果您需要数组元素的副本,或者允许您从中移动,则会出现问题

例如:

class Player
{
public:
    void setInventory(std::string inventory[]) {
        std::copy(inventory, inventory + 4, this->inventory);
    }
private:
    std::string inventory[4];
};
请注意,您应该确保您的“数组参数”(实际上是指针)应该(至少)包含所需的4个元素。如果可能,最好将大小编码到类型中,例如使用

struct播放器{
void setInventory(标准::数组i){
存货=i;
}
阵列清单;
};

这是因为
std::array
实现了赋值操作符
操作符=

您不会使用
stdncpy()
库存
std::string
的数组,而不是
char

您可以编写一个简单的循环来执行此操作

void setInventory(string inventory[]) {
    for (int i = 0; i < 4; i++) 
        this->inventory[i] = inventory[i];
}

您应该真正地将库存存储划分为一个类型或类本身,以便能够统一和清晰地对待它。这将自动让您执行复制/移动操作(假设使用最新的符合标准的编译器),以保持处理清晰:

typedef std::array<std::string, 4> Inventory;

class Player
{
public:
    void setInventory(Inventory &&inventory) {
        this->inventory = inventory;
    }
private:
    Inventory inventory;
};
typedef std::数组清单;
职业选手
{
公众:
作废设置库存(库存和库存){
此->库存=库存;
}
私人:
存货;
};
这样做还可以让您在将来扩展和增强
库存
本身,从外部处理它的代码的重构为零或最小。

我建议您了解。或者大约。
class Player
{
public:
    void setInventory(const std::array<std::string, 4>& inventory) { this->inventory = inventory; }
private:
    std::array<std::string, 4> inventory;
};
typedef std::array<std::string, 4> Inventory;

class Player
{
public:
    void setInventory(Inventory &&inventory) {
        this->inventory = inventory;
    }
private:
    Inventory inventory;
};