【问题标题】:Pure virtual assignment operator in c++C++中的纯虚拟赋值运算符
【发布时间】:2019-02-01 10:34:30
【问题描述】:

我有一个基类

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

【问题讨论】:

  • 你分配指针...this way
  • @user1810087 *d1 = *d1_another?
  • @PavloKovalov:试试看。
  • 没错,见链接:)
  • 赋值和派生类不能很好地配合。将它们结合起来往往是一个设计错误。您永远不会分配任何基础或派生对象。您只是在分配指针。

标签: c++


【解决方案1】:

这样试试

#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;

【讨论】:

  • 为什么要在D1D2 中添加虚拟析构函数?不是虚拟的不行吗?
  • @PavloKovalov 因为如果你想使用一些原始指针,那么它是必要的
  • 如果基类析构函数是虚拟的,那么派生类的析构函数也是虚拟的,你不需要明确指定它是虚拟的
  • 所以派生类~destructor()virtual ~destructor()一样,如果base有虚析构函数?
  • @PavloKovalov 是的
猜你喜欢
  • 2011-04-15
  • 2010-10-14
  • 2017-12-10
  • 2019-10-21
  • 2012-12-02
  • 2016-10-01
  • 2013-06-11
  • 1970-01-01
  • 2018-06-21
相关资源
最近更新 更多