打印具有通用特定变量值的类对象

Print class objects with specific variable value in common

本文关键字:变量值 对象 打印      更新时间:2023-10-16

如果你从同一个类中调用了main中的三个对象,如下所示:

customer one(856756, "New York");
customer two(896557, "New York");
customer three(896571, "Washington");

当你有这样的课程时,你怎么能打印出一个拥有相同城市的人的列表:

class customer {
public:
customer(int RegNr, string City) { this->RegNr = RegNr; this->City = City; }
customer(){}
~customer() { cout << "Customer with registration number " << RegNr << " has been destroyed." << endl; }
void setRegNr(int RegNr){this->RegNr=RegNr;}
void setCity(int City) { this->City; }
string getCity() const { return City; }
int getRegNr() const { return RegNr; }
private:
int RegNr;
string City;
};

首先,你的setCity是错误的,它不要求string,也没有设置任何东西。使用一些 mem 初始化列表和一些最佳实践,我们得到:

class Customer 
{
public:
Customer (int regNr, string city) : city(city), regNr(negNr) {}
Customer(){}
~Customer() { cout << "Customer with registration number " << regNr << " has been destroyed." << endl; }
void setRegNr (int nr) { regNr = nr;}
void setCity(string city) { this->city = city; }
string getCity() const { return city; }
int getRegNr() const { return regNr; }
private:
int regNr;
string city;
};

现在,当您有 3 个对象时:

Customer one(856756, "New York");
Customer two(896557, "New York");
Customer three(896571, "Washington");

要迭代这些,最好将它们放入数组中:

std::array<Customer, 3> customers = {one, two, three};

现在我们可以循环元素并打印出城市是否相同:

for(int i = 0; i < customers.size(); ++i)
{
for(int j = 0; j < customers.size(); ++j)
{
if(j == i)
continue;
if(customers[i].getCity() == customers[j].getCity())
{
std::cout << "City with regnr " << customers[i].getRegNr() << " and " << customers[j].getRegNr() << " have the same city.n";
}
}
}

您可以在<algorithm>中使用一些函数来加快速度/为同一事物编写更少的代码,但写出循环使其更容易理解。