注意:如果采用以下方式构造,那么类中必须存在并且只能存在无参构造和有参默认构造中的其一
#include<iostream>
#include<vector>
using namespace std;
class Person
{
public:
string name;
int age;
Person(string name = "1", int age = 2) :name(name), age(age) {};
Person(string name , int age )
{
this->name = name;
this->age = age;
};
void toString()
{
cout << "Person ";
cout << "[name=" << this->name << "," << " age=" << this->age << "]" << endl;
}
};
int main()
{
Person p[5];
int n, age;
cin >> n;
string name;
for (int i = 0; i < n; i++)
{
cin >> name >> age;
p[i].name = name;
p[i].age = age;
p[i].toString();
}
string myname;
cin >> myname;
for (int i = 0; i < n; i++)
{
if (p[i].name == myname)
{
p[i].toString();
return 0;
}
}
cout << "此人不存在" << endl;
return 0;
}