打印具有通用特定变量值的类对象
Print class objects with specific variable value in common
如果你从同一个类中调用了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>
中使用一些函数来加快速度/为同一事物编写更少的代码,但写出循环使其更容易理解。
相关文章:
- 使用变量值作为 PlaySound 中的路径
- 通过指针偏移量访问结构变量值
- 变量值在 C++ 中的 glutIdleFunc() 中未递增
- 更新 #ifdef 中的现有变量值?
- 尝试更改 main 函数内的全局变量值时出现编译错误 C++.
- 通过 Rcpp 和 bit64 R 包将最大的int64_t变量值从 C++ 传递到 R
- 如何使用 IRBuilder 更新 LLVM IR 中的全局变量值?
- 更改已在运行的程序的变量值
- 在 Xcode 中使用后对外部变量值进行初始化
- C++整数变量值
- 打印具有通用特定变量值的类对象
- 如何根据基类对象中的变量值分配派生类中的变量?
- 我使用箭头运算符打印出对象的变量值,并得到一些随机值作为输出
- 如何访问类对象的每个实例的静态变量值
- 对象变量值的C 连续检查产生不同的结果
- 对象在将操作推送到向量后成员变量值已更改
- 如何更改类中对象向量中对象的变量值
- C++ 设计一个对象,使其采用变量值和规则来应用于它们
- 如何从变量值初始化对象
- 为什么我的析构函数没有破坏我的对象,它仍然保留其成员变量值