运算符 = 覆盖 c++

Operator = override c++

本文关键字:c++ 覆盖 运算符      更新时间:2023-10-16

我正在尝试覆盖我的=运算符。我有 2 个指针父级,他们需要是指针。

P1* 和 P2*

这是我在父级内部的覆盖

Parent Parent::operator=(const Parent& otherParent) const
    {
        return Parent(otherParent);
    }

这是我的复制构造函数:

Parent::Parent(const Parent& otherParent) : myChild("") {
    this->name = otherParent.GetParentName();
    myChild = Child(otherParent.GetChild());
}

这是我的主要:

#include <iostream>
#include "Parent.h"
#include "Child.h"
using namespace std;
int main() {
    Child c1 = Child("rupert");
    Parent* p1 = new Parent("Parent1", c1);
    cout << *p1 << endl;
    Child c2 = Child("bob");
    Parent* p3 = new Parent("Parent3", c2);
    cout << *p3 << endl;
    *p3 = *p1; 
    cout << *p3 << endl;
    cin.get();
    return 0;

}

为什么打印出这个:

父名:

父1 子名:鲁珀特

父名称:

父3 子名称:鲍勃

父名称:

父3 子名称:鲍勃

第三次打印应与第一次相同。

将赋值语句*p3 = *p1视为如下工作:

p3->operator=(*p1);

这是有效的语法。如果你这样看,你应该能够看到赋值运算符需要修改this如果它实际上要做任何赋值。现在,您创建并返回一个立即销毁的临时。