这是我的代码
#include <iostream>
#include <string>
class Person {
private:
int pancakesEaten, personID;
public:
Person() {
pancakesEaten = 0;
personID = setID();
}
static int setID() {
static int currID;
return currID++; // Returns currID and then increments.
}
bool operator>=(const Person& p);
bool operator<=(const Person& p);
void askPancakesEaten();
void print();
};
bool Person::operator>=(const Person& p) {
if(this->pancakesEaten >= p.pancakesEaten) {
return true;
}
return false;
}
bool Person::operator<=(const Person& p) {
if(this->pancakesEaten <= p.pancakesEaten) {
return true;
}
return false;
}
void Person::askPancakesEaten() {
std::cout << "Please enter how many pancakes you ate: ";
std::cin >> this->pancakesEaten;
}
void Person::print() {
std::cout << this->personID;
std::cout << "Person " << this->personID << " ate " << this->pancakesEaten << " pancakes";
}
int main() {
Person people[10];
for(int i = 0; i<10; i++) {
Person currPerson;
currPerson.askPancakesEaten();
currPerson.print();
}
}
我的问题是,我正在尝试初始化 10 个 Person 对象的数组,并且由于我的静态方法,当我进入 for 循环时,它使我的静态计数从 10 开始。
我知道我可以通过更改构造函数并摆脱 setID 并使用 i 来轻松解决这个问题,但我很好奇是否还有其他方法可以解决这个问题?
最佳答案
... but I am curious if there is another way around it.
为什么要初始化一个数组而不在循环中使用它?
for(int i = 0; i<10; i++) {
people[i].askPancakesEaten();
people[i].print();
}
除了 setID()
的命名有点令人遗憾(getNextID()
在我看来可能是一个更好、更清晰的选择),该实现没有任何问题,因为您拥有它。
此外,最好将此函数设置为私有(private)
,因为如何保存和管理这些 ID 对于类实例来说是唯一的,这是一个实现细节,不应公开访问。
关于c++ - 如何使用静态 ID 计数器初始化用户定义对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65014539/