我刚开始接触 OO,我有一个关于构造函数的问题。这只会用不同的参数 i 一遍又一遍地创建相同的对象“Team a”,对吗?
for (int i = 1; i < n+1; i++) Team a (i); // construct teams
如果我知道必须有多少个团队,我该如何创建不同的“团队”,即团队 a、团队 b ... 团队 h?参数 i 不能同时是属性和名称吗(Team 1,Team 2..)?
非常感谢您提供任何提示或帮助!
Pd:这是我正在使用的构造函数(如果您需要更多代码,请在评论中写下):
public:
//constructors
Team(int n); // (this will set number to n and points, goals_scored, goals_lost to 0)
最佳答案
您可以使用 std::vector :
std::vector<Team> teams;
for(int i = 0; i < n; ++i)
teams.emplace_back(i + 1); // makes Team(i + 1) in vector
注意:std::vector
使用基于零的索引,因此您的团队 #1 是索引 0:
teams[0]; // team #1
teams[1]; // team #2
teams[n]; // team #n + 1
关于c++ - for循环中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35888643/