基本上我正在试验多态性。我有 2 个对象,一个客户和一个员工。客户有姓名和投诉。雇员有姓名和薪水。
在一个循环中,我接受这些参数并创建一个新的 Person 以添加到数组中。
但这是我的问题:如果我在字符串中放了任何空格,循环就会跑到最后。
Person *persons[10];
for (int i = 0; i < sizeof persons;i++)
{
cout<<"Please type 1 for customer or 2 for Employee"<<endl;
int q;
cin>>q;
string name;
int salary;
string complaint;
if (q == 1)
{
cout<<"What is your name?"<<endl;
cin>>name;
cout<<"What is your complaint"<<endl;
cin>>complaint;
personPtr = new Customer(name,complaint);
cout<<"Created customer"<<endl<<endl;
persons[i] = personPtr;
cout<< "added to array"<<endl<<endl;
}
else if(q==2)
{
cout<<"What is your name?"<<endl;
cin>>name;
cout<<"What is your salary"<<endl;
cin>>salary;
personPtr = new Employee(name,salary);
persons[i] = personPtr;
}
else
{
cout<<"Sorry but i could not understand your input. Please try again"<<endl;
i--;
cin>>q;
}
}
delete personPtr;
system("PAUSE");
有什么特殊的方法可以包含字符串吗?
这是客户和员工类供参考。
class Person
{
public:
Person(const string n)
{name = n;}; // initialise the name
virtual void printName();
protected:
string name;
};
class Customer:public Person
{
public:
string complaint;
Customer(string name, string cm)
:Person(name)
{
complaint=cm;
}
virtual void printName();
};
class Employee:public Person
{
public:
int salary;
Employee(string name,int sl)
:Person(name)
{
salary = sl;
}
virtual void printName();
};