gpt4 book ai didi

c++ - 如何在 C++ 中将对象属性设置为先前初始化的数组

转载 作者:行者123 更新时间:2023-11-28 00:19:41 25 4
gpt4 key购买 nike

我想采用先前初始化的对象数组,并能够将其设置为类变量。

我在指针或出色的编码风格方面经验不多。

这是我正在处理的隔离问题的代码片段:

#include<cstdlib>
#include<iostream>

using namespace std;

class GameBoard {
string players[];
int total_players;
public:
GameBoard (string given_players[]) {
players = given_players;
total_players = sizeof(given_players)/sizeof(*given_players);
}
};

int main () {
string players[] = {
"Jack",
"Jill"
};
GameBoard gb(players);
return 0;
}

目前,这段代码输出错误:

In constructor 'GameBoard::GameBoard(std::string*)':
[Error] incompatible types in assignment of 'std::string* {aka std::basic_string<char>*}' to 'std::string* [0] {aka std::basic_string<char>* [0]}'

最佳答案

更好的方法

#include <vector>
#include <string>

class GameBoard {
std::vector<std::string> players;
int total_players;
public:
GameBoard (const std::vector<std::string> & p_players):
players(p_players),
total_players(p_players.size())
{
}
};

然后

int main()
{
std::vector<std::string> players{"jill", "bill"}; //if C++11 is not available you can use push_back()
GameBoard b{players};
return 0;
}

关于c++ - 如何在 C++ 中将对象属性设置为先前初始化的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28179744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com