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

标签 c++

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

相关文章:

c++ - 当我声明字符串数组时,C++ 如何计算偏移地址

c++ - 交叉编译QT时附加定义

c++ - 使用 boost::make_shared 创建 vector 元素无法正常工作

c++ - 如何在 C++ 中有效地将集合格式化为字符串?

c++ - Eclipse CDT 构建输出到 bin/Release 和 bin/Debug

c++ - 如何优化以下公共(public)循环?

c++ - 我可以告诉 Boost.MPI 哪个类版本与 Boost.Serialization 一起使用吗?

c++ - 遍历结构内部的数组

c++ - `#include <iostream>` 和 `-std=c++0x` 坏了

C++ 静态库