我想采用先前初始化的对象数组,并能够将其设置为类变量。
我对指针或编码风格没有很多经验。
这是我正在处理的代码片段,它将问题隔离开来:
#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]}'
答案 0 :(得分:3)
更好的方法
#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;
}