gpt4 book ai didi

c++ - 使用继承重载 = 运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:21 25 4
gpt4 key购买 nike

嘿,我想了解如何在存在继承时重载 operator=没有成功。代码示例:

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);
}

现在假设 Student 从 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);
}

非常感谢,非常感谢。

最佳答案

virtual 赋值运算符对我来说似乎是一种厌恶。赋值适用于值类型,而虚拟适用于多态类型。这两个几乎处于光谱的两端。

暂时想象一下这段代码:

void foo(person& x, const person& y)
{
x = y;
}

另外我们还有这个

class teacher : public person {...};
class student : public person {...};

现在我们称它为:

teacher t;
student s;

foo(s,t);

那应该怎么办?把学生变成老师?为何如此?

关于c++ - 使用继承重载 = 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3866773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com