C++程序作业: 定义一个公司类 题目具体看图,谢谢大家! 100
展开全部
#include <string>
struct Staff
{
std::string name;
std::string job;
};
class Company
{
private:
std::string name;
std::string generalManager;
std::string deputyGeneralManager;
Staff *staffs;
int staffsNumber;
static Staff* allocStaffs(const Staff *staffs, int number)
{
Staff *p = new Staff[number];
for (int i = 0; i < number; i++)
p[i] = staffs[i];
return p;
}
public:
Company(const std::string &name, const std::string &generalManager, const std::string &deputyGeneralManager, const Staff *staffs, int staffsNumber)
: name(name), generalManager(generalManager), deputyGeneralManager(deputyGeneralManager),
staffs(allocStaffs(staffs, staffsNumber)), staffsNumber(staffsNumber)
{
}
~Company()
{
delete[] staffs;
}
Staff& operator[](int i)
{
if (i >= staffsNumber)
throw i;
return staffs[i];
}
private:
Company(const Company &r)
: Company(r.name, r.generalManager, r.deputyGeneralManager, r.staffs, r.staffsNumber)
{
}
Company& operator=(const Company &r) = delete;
friend Company operator+(const Company &l, const Company &r);
};
Company operator+(const Company &l, const Company &r)
{
Company result(l.name + r.name, l.generalManager, r.generalManager, nullptr, 0);
delete[] result.staffs;
result.staffs = new Staff[l.staffsNumber + r.staffsNumber];
for (int i = 0; i < l.staffsNumber; i++)
result.staffs[i] = l.staffs[i];
for (int i = 0; i < r.staffsNumber; i++)
result.staffs[l.staffsNumber + i] = r.staffs[i];
result.staffsNumber = l.staffsNumber + r.staffsNumber;
return result;
}
int main()
{
Company c1("c1", "m1", "", nullptr, 0);
Staff c2Staffs[] = { { "s1", "j1" }, { "s2", "j2" } };
Company c2("c2", "m2", "", c2Staffs, 2);
Company &c3 = c1 + c2;
Staff &c3s1 = c3[0];
Staff &c3s2 = c3[1];
return 0;
}
更多追问追答
追问
这个可以吗?你写过的作业吗?还是刚刚写的?
追答
刚写的,如果这个不行,你们老师就要多学学了
其实这道题,出的就有毛病,不能拷贝构造,那重载+号基本也就没多大意义了,你们老师不太严谨
还有,到底是公司还是实验室?怎么开始还没有,写着写着就多出个副总经理?他这么不用心,没理由对作业吹毛求疵,反正他要求的我都做到了
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询