【发布时间】:2016-02-20 20:42:35
【问题描述】:
我有一个可以创建多个对象的类。
class Employee{
public:
string firstName;
string lastName;
string gender;//gender - if necesary
string identificationCode;//an Id for every employee
string typeOfEmployee;//is Programmer, is Tester and so on...
string getFirstName(){ return this->firstName; } //show the name
string getLastName(){ return this->lastName; }//show the name
string getGender(){ return this->gender; }//show the gender - if necesary
string getID(){ return this->identificationCode; }//show ID
string getTypeOfEmployee(){ return this->typeOfEmployee; }//show type of job
};
class Programmer : public Employee{
public:
vector<string> knownLanguages;//array of known programming languages
unsigned int countProgrammers;
}programmer[5];
Programmer::Programmer()
{
countProgrammers++;
}
int main(){...
switch (checkJob(getTokens[3]))
{
case 1:
Programmer programmer[counter];//this is error = expression must be a value
programmer[counter].identificationCode = getTokens[0];
programmer[counter].firstName = getTokens[1];
programmer[counter].lastName = getTokens[2];
programmer[counter].typeOfEmployee = getTokens[3];
programmer[counter].knownLanguagessplitString(getTokens[4], SecondDelimiter);
//cout << programmer[counter].firstName<<" " << programmer[counter].lastName<<" with ID: " << programmer[counter].identificationCode<<" is a "<<programmer[counter].typeOfEmployee<<" and knows " << endl;
counter++;
break;
...}
我想使用一个计数器,当一个新对象被创建时,或者当我使用一个流控制结构来为一个对象添加更多细节时,我想增加它。
我的偏好是我想把它放在课堂上。
到目前为止,我已经定义了countProgrammers,但是因为我使用的是programmer[1] 等等,所以对于我创建的每个程序员来说,这将是一个不同的值。
有没有办法将变量保留在类中,但主动向我显示我创建的总对象的数量,如果我称之为
cout<<programmer.countProgrammers;(这是不正确的,因为我定义类的方式,正确的方式应该是cout<<programmer[1].countProgrammers;,但它会为创建的 wach 对象显示不同的值,例如,对于第三个对象它将是 3等等)//已解决
【问题讨论】: