运行代码:
//类定义练习
#include"std_lib_facilities.h"
#include"GUI/Simple_window.h"
#include"GUI/GUI.h"
#include"GUI/Graph.h"
#include"GUI/Point.h"
//定义类
class Person
{
private:
string first_name;
string second_name;
int person_age;
public:
Person(string Snn,string Fnn , int aa);
Person() { second_name = "";first_name=""; person_age = -1; };
string name() { return second_name+" "+first_name; }
int age() { return person_age; }
void set_name(string Snn,string Fnn);
void set_age(int aa);
};
Person::Person(string Snn,string Fnn , int aa )
{
if (aa < 0 || aa >= 150)error("wrong age!");
string nn = Snn + Fnn;
for (int i = 0; i < nn.size(); i++)
{
if (nn[i] == ';' || nn[i] == ':' || nn[i] == '"' || nn[i] == '\'' || nn[i] == '['
|| nn[i] == ']' || nn[i] == '*' || nn[i] == '&' || nn[i] == '^' || nn[i] == '%'
|| nn[i] == '$' || nn[i] == '#' || nn[i] == '@' || nn[i] == '!')
error("wrong name");
}
second_name = Snn;
first_name = Fnn;
person_age = aa;
}
void Person::set_name(string Snn,string Fnn)
{
string nn = Snn + Fnn;
for (int i = 0; i < nn.size(); i++)
{
if (nn[i] == ';' || nn[i] == ':' || nn[i] == '"' || nn[i] == '\'' || nn[i] == '['
|| nn[i] == ']' || nn[i] == '*' || nn[i] == '&' || nn[i] == '^' || nn[i] == '%'
|| nn[i] == '$' || nn[i] == '#' || nn[i] == '@' || nn[i] == '!')
error("wrong name");
}
second_name = Snn;
first_name = Fnn;
}
void Person::set_age(int aa)
{
if (aa < 0 || aa >= 150)error("wrong age!");
person_age = aa;
}
//-----------------------------------------------------------------------------
//定义类Person的输出操作符<<
ostream& operator <<(ostream& os,Person& pp)
{
os << "name: " <<"\t" << pp.name() << "\n" << "age: " << "\t" << pp.age() << "\n";
return os;
}
//----------------------------------------------------------------------------
//定义类Person的输入操作符
istream& operator>>(istream& is, Person& pp)
{
string Snn="";
string Fnn="";
int aa=-1;
is >> Snn >> Fnn>> aa;
istringstream iss(Fnn);
int string_to_number = 0;
if (iss >> string_to_number)error("incomplicated name--", Snn);
pp.set_name(Snn,Fnn);
if (aa >=0 &&aa < 150) { pp.set_age(aa); }
return is;
}
//-----------------------------------------------------------------------------
int main()
try
{
cout << "输入格式:Second name First name age:\n";
Person pp,pp0;
vector<Person>pps;
while (cin >> pp)
{
pps.push_back(pp);
pp = pp0;
}
for (int i = 0; i < pps.size(); i++)
{
cout << pps[i]<<"\n";
}
return 0;
}
catch (exception& e) {
cerr << "error:" << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Oops:unknown exception!\n";
keep_window_open();
return 2;
}
运行结果: