使用继承重载=运算符

Nad*_*ern 1 c++ operator-overloading

嘿,我试图了解如何重载运算符=当存在没有成功的继承.代码示例:

class Person 
{
    private:
            char* m_name;
            char* m_lastName;
    ..... 
    public:
            virtual Person& operator=(const Person& other);
};
/********************/
cpp implementation
/********************/
#include "Person.h"
Person& Person:: operator=(const Person& other)
{
     if(this == &other)
         return *this;
     delete[] m_name;
     delete[] m_lastName;
     if (other.m_name!=NULL)
     {
         m_name = new char[strlen (other.m_name)+1];
         strcpy(m_name,other.m_name);
     }
     if (other.m_lastName!=NULL)
     {
         m_lastName = new char[strlen (other.m_lastName)+1];
         strcpy(m_lastName,other.m_lastName);
     }
     return (*this);
}
Run Code Online (Sandbox Code Playgroud)

现在让我们说学生从Person继承应该如何实现=运算符我认为应该如下所示请更正我因为我可能是错的:

#include "Person.h"
class Student : public Person
{
    private:
            char* m_collageName;
    ..... 
    public:
            virtual Person& operator=(const Person& other);
};
/********************/
cpp implementation
/********************/
#include "Student.h"
Person& Student:: operator=(const Person& other)
{
     if(this == &other)
         return *this;
     Person::operator=(other);
     delete[] m_collage;
     if ((Student)other.m_collageName != NULL)
     {
        m_collageName = new char[strlen((Student)other.m_collageName)+1];
        strcpy(m_collageName,(Student)other.m_collageName);
     }
     return (*this);
}
Run Code Online (Sandbox Code Playgroud)

非常感谢很多appriciate它.

sbi*_*sbi 9

一个virtual赋值运算符似乎是一个憎恶我.赋值用于值类型,而virtual用于多态类型.而这两者几乎都在频谱的两端.

想象一下,这段代码:

void foo(person& x, const person& y)
{
  x = y;
}
Run Code Online (Sandbox Code Playgroud)

再加上我们有这个

class teacher : public person {...};
class student : public person {...};
Run Code Online (Sandbox Code Playgroud)

现在我们称之为:

teacher t;
student s;

foo(s,t);
Run Code Online (Sandbox Code Playgroud)

该怎么办?把学生变成老师?怎么会这样?