gpt4 book ai didi

c++ - 运算符 = 覆盖 c++

转载 作者:行者123 更新时间:2023-11-28 01:54:49 24 4
gpt4 key购买 nike

我正在尝试覆盖我的 = 运算符。我有 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;

}

为什么会打印出这个:

父名:Parent1 子名:rupert

parent 姓名:Parent3 child 姓名:bob

parent 姓名:Parent3 child 姓名:bob

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

最佳答案

将赋值语句 *p3 = *p1 想象成这样:

p3->operator=(*p1);

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

关于c++ - 运算符 = 覆盖 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41582645/

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