我有班级员工
class Employee{
protected:
char* name
public:
Employee();
virtual ~Employee();
float getSalary() = 0; // pure virtual funtion
virtual Employee& operator = (const Employe& temp);
}
和派生类productEmployee
class productEmployee:public Employee{
protected:
int product;
public:
productEmployee();
virutal ~productEmployee();
float getSalary();
virtual productEmployee& operator = (const productEmployee& temp);
}
Operator= 用于两个类 雇员类
Employee& Employee::operator = (const Employee& temp) {
if (this != &temp) {
this->~Employee();
name = new char[100]();
strcpy_s(name, 100, temp.name);
}
return *this;
}
一流产品员工
productEmployee& productEmployee::operator = (const productEmployee& temp) {
if (this != &temp) {
//this->~productEmployee();
Employee::operator=(temp);
product = temp.product
}
return *this;
}
当我在 main 中创建时:
Employee *t1 = new productEmployee()
Employee *t2 = new productEmployee()
t1->input()...
*t2=*t1 //(t2=t1 is wrong, memory leak)
它不起作用,t1 和 t2 现在有相同的地址,我想要 t1!=t2 和 t1->name != t2->name(地址),我如何编辑 operator= 来得到它?
您最近的更改使代码更好,但仍不会调用您的赋值运算符。
那是因为你没有覆盖子类中的赋值运算符。要覆盖虚函数,您必须使用完全相同的参数和限定符。我建议您养成对所有重写函数使用
override
特殊标识符的习惯,因为如果您实际上没有重写函数,这将导致编译器报错。正如 here 所示(请注意,我修复了您代码中的许多其他错误以使其正常工作)。
作为一个简单的解决方案,根本不要使用虚拟赋值运算符。相反,在基类
Employee
中只有(非虚拟)赋值运算符,然后调用虚拟 copy
(或类似名称的)函数。 productEmployee
类(正确地)覆盖它,并将 downcast 参数转换为内部的正确类型。
也许是这样的:
class Employee
{
// Other functions and members
protected:
virtual Employee& copy(Employee const& other)
{
// TODO: Implement copying of Employee objects...
return *this;
}
public:
Employee& operator=(Employee const& other)
{
return copy(other);
}
};
class productEmployee : public Employee
{
// Other functions and members
protected:
Employee& copy(Employee const& other) override
{
productEmployee const& real_other = static_cast<productEmployee const&>(other);
// TODO: Implement copying of productEmployee objects, using real_other...
// This is needed to invoke the parents copy function
return Employee::copy(other);
}
};
此更改后,您的(适当的对象)分配
*t2 = *t1;
应该工作正常(假设
copy
功能做他们应该做的事)。
注意
copy
函数做它应该做的事情,你可以通过不使用 char*
来简化它。对所有字符串使用std::string
,复制字符串是一个简单的赋值问题。
感谢以上来自一些程序员的回答,从这里,我已经通过我的方式解决了这个问题:
类员工
virtual NhanVien* clone() = 0;
一流产品员工
Employee* productEmployee::clone() {
productEmployee* p = new productEmployee();
if (p == NULL) return NULL;
strcpy_s(p->name, 100, this->name);
p->product = this->product;
return p;
}
现在我只需要
NhanVien *t2 = t1->clone(); // It works with me