【问题标题】:Print class objects with specific variable value in common打印具有共同特定变量值的类对象
【发布时间】:2019-10-17 18:23:58
【问题描述】:

如果你从同一个类中调用 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;
};

【问题讨论】:

  • 比较每个实例的getCity() 输出
  • @ignacio 如果我比较客户一和二,它只会检查这两个。如何“动态”比较它们,以便比较创建的每个新对象?
  • 要动态比较它们,您必须创建一个数组。

标签: c++ class object


【解决方案1】:

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

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";
    }
  }
}

您可以在 &lt;algorithm&gt; 中使用一些函数来加快速度 / 同一件事的代码更少,但写出循环更容易理解。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 2018-05-13
    • 2022-01-15
    相关资源
    最近更新 更多