我正在编辑它,现在好了,我应用了一个空的构造函数,并且我的代码工作了,但是这种方式:
名称1 S名称1 1000 0.2 100 Name2 SName2 1000 0.3 750
此代码通常可以正常运行,我的老师特别希望我们使用“ this->”和“ * this”,所以这是我的代码: 我的.h文件
#ifndef COMEMPLOYEE_H
#define COMEMPLOYEE_H
#include <string>
using namespace std;
class ComEmployee
{
protected:
string firstName;
string lastName;
static int ID;
double grossSale;
double comRate;
public:
ComEmployee();
ComEmployee(string, string, double, double);
ComEmployee& setfirstName(string);
ComEmployee& setlastName(string);
ComEmployee& setgrossSale(double);
ComEmployee& setcomRate(double);
string getfirstName();
string getlastName();
double getgrossSale();
double getcomRate();
int getID() const;
double calCom() const;
void Display() const;
};
#endif
我的.cpp文件
#include "ComEmployee.h"
#include <iostream>
using namespace std;
int ComEmployee::ID = 1000;
ComEmployee::ComEmployee(){}
ComEmployee::ComEmployee(string name, string lname, double gs, double comr)
{
this->firstName = name;
this->lastName = lname;
this->grossSale = gs;
this->comRate = comr;
++ID;
}
int ComEmployee::getID() const
{
return ID;
}
ComEmployee & ComEmployee::setfirstName(string name)
{
firstName = name;
return *this;
}
ComEmployee & ComEmployee::setlastName(string lname)
{
lastName = lname;
return *this;
}
ComEmployee & ComEmployee::setgrossSale(double gs)
{
grossSale = gs;
return *this;
}
ComEmployee & ComEmployee::setcomRate(double comr)
{
comRate = comr;
return *this;
}
string ComEmployee::getfirstName()
{
return firstName;
}
string ComEmployee::getlastName()
{
return lastName;
}
double ComEmployee::getgrossSale()
{
return grossSale;
}
double ComEmployee::getcomRate()
{
return comRate;
}
double ComEmployee::calCom() const
{
return grossSale*comRate;
}
void ComEmployee::Display() const
{
cout << firstName << " " << " " << getID() << " " << comRate << " " << calCom() << endl;
}
这是我的main.cpp文件
#include <iostream>
#include "ComEmployee.h"
using namespace std;
int main()
{
ComEmployee employee, employee2;
employee.setfirstName("Name1").setlastName("SName1").setgrossSale(500).setcomRate(0.2).Display();
employee2.setfirstName("Name2").setlastName("SName2").setgrossSale(2500).setcomRate(0.3).Display();
system("pause");
}
我希望输出为:
Name1 SName1 1001 ... Name2 SName2 1002 ...
答案 0 :(得分:0)
在类定义中添加一些int变量:
int m_ID;
然后,您需要在cpp文件中使用默认构造函数:
// cpp
ComEmployee::ComEmployee()
{
m_ID = ID++;
}
并修改您的GetID函数:
int ComEmployee::GetID() const
{
return m_ID;
}
答案 1 :(得分:0)
您必须稍微更改设计。由于ID
是员工ID,因此它不能是static
变量。 static
变量属于类,而不是的特定实例
班级。
将ID
定义为该类的普通成员。
您可以使用新的static
变量CurrentID
来跟踪员工。
如下定义后,
int ComEmployee::CurrentID = 1000;
在默认和非默认构造函数中,执行以下操作:
this->ID = CurrentID++;