|
程序来自:http://www.d2school.com/bhcpp_book/3_11.php
具体见下面:
问题出在“cin.sync();”吧,谁解释下?
#include <iostream>
#include <string>
using namespace std;
struct Person
{
public:
Person()
{
cout << "Wa~Wa~" << endl;
cout << "为这个哇哇哭的人,起个名字吧:";
getline(cin, name);
}
virtual ~Person()
{
cout << "Wu~Wu~" << endl;
}
string GetName()
{
return name;
}
virtual void Introduction()
{
cout << "Hi, my name is " << name << "." << endl;
}
private:
std::string name;
};
struct Beauty : public Person
{
virtual ~Beauty()
{
cout << "wu~wu~人生似蚍蜉、似朝露;似秋天的草,似夏日的花……" << endl;
}
virtual void Introduction()
{
cout << "大家好,我是美女: " << GetName() << ",请多多关照!" << endl;
}
};
int main()
{
while(true)
{
Person *someone;
cout << "请选择(1/2/3):" << endl
<< "1----普通人" << endl
<< "2----美人" << endl
<< "3----退出" << endl;
int sel = 0;
cin >> sel;
if (cin.fail())
{
cin.clear();
}
cin.sync();
if (3 == sel)
{
break;
}
if (1 == sel)
{
someone = new Person;
}
else if (2 == sel)
{
someone = new Beauty;
}
else //用户输入的,即不是1,也不是2,也不是3...
{
cout << "输入有误吧?请重新选择。" << endl;
continue;
}
cout << someone->GetName() << "的自我介绍:" << endl;
someone->Introduction();
delete someone;
}
return 0;
} |
|