我的代码也可以在这里找到。
这段代码可以工作(但有很多代码重复):
Employee::Employee(const Employee& x)
{
name=new char [strlen(x.name)+1];
strcpy(name, x. name);
strcpy(EGN, x.EGN);
salary=x.salary;
}
void Employee::operator=(const Employee& x)
{
delete[] name;
name=new char [strlen(x.name)+1];
strcpy(name, x. name);
strcpy(EGN, x.EGN);
salary=x.salary;
}
Employee::Employee(char* n, char* e, double s)
{
name = new char [strlen(n)+1];
strcpy(name, n);
strcpy(EGN, e);
salary=s;
}
下面是我试图避免写三遍相同的东西......但它不起作用。难道不能让代码更短吗?
Employee::Employee(char* n, char* e, double s)
{
name = new char [strlen(n)+1];
strcpy(name, n);
strcpy(EGN, e);
salary=s;
}
Employee::Employee(const Employee& x)
{
Employee(x.name, x.EGN, x.salary);
}
void Employee::operator=(const Employee& x)
{
delete[] name;
Employee(x);
}