C++ 中的纯虚拟赋值运算符

Pure virtual assignment operator in c++

本文关键字:虚拟 赋值运算符 C++      更新时间:2023-10-16

>我有一个基类

class Base{
public:
virtual ~Base();
};

我从 Base 派生了两个类:

class D1:public Base{
//...some fields
//assignment operator, it does the deep copy of the members
D1& operator=(const D1&);
};
class D2:public Base{
//...some fields
//assignment operator, it does the deep copy of the members
D2& operator=(const D2&);
};

接下来,总的来说,我有两个对象,比如说D1.问题是永远不会调用覆盖的赋值运算符,但是调用 base 的默认运算符。我试图在Base中使赋值运算符成为虚拟,但没有帮助。

D1 *d1 = new D1();
D1 *d1_another = new D1();
//this doesn't work:
d1 = d1_another
D2 *d2 = new D2();
D2 *d2_another = new D2();
//this doesn't work:
d2 = d2_another

UPD我也想知道如何处理

Base *d1 = new D1();
Base *d1_another = new D1();
//?
d1 = d1_another

像这样试试

#include <iostream>
#include <string>
using namespace std;
class Base {
    public:
    virtual ~Base() {}
};

class D1 : public Base {
public:
    virtual ~D1() {}
    //...some fields
    //assignment operator, it does the deep copy of the members
    D1& operator=(const D1&) {
        cout << "D1:operator=(const D1&)n";
        return *this;
    }
};
class D2 : public Base {
public:
    virtual ~D2() {}
    //...some fields
    //assignment operator, it does the deep copy of the members
    D2& operator=(const D2&) {
        cout << "D2:operator=(const D2&)n";
        return *this;
    }
};

主要

    D1 *d1 = new D1();
    D1 *d1_another = new D1();
    //this doesn't work:
    *d1 = *d1_another;
    D2 *d2 = new D2();
    D2 *d2_another = new D2();
    //this doesn't work:
    *d2 = *d2_another;