C++ 中的纯虚拟赋值运算符
Pure virtual assignment operator in c++
>我有一个基类
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;
相关文章:
- 重载Singly Linked List中的赋值运算符
- 使用赋值运算符重载从类中返回jobject
- 标准库类型的赋值运算符的引用限定符
- 复制构造函数、赋值运算符C++
- 标准::变体的赋值运算符
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 基类和派生类的多态赋值运算符
- 为用户定义的类正确调用复制构造函数/赋值运算符
- CRTP 中的复制赋值运算符 - gcc vs clang 和 msvc
- 为什么初始化时没有调用重载赋值运算符?
- 赋值运算符重载和自赋值
- C++矢量复制构造函数和赋值运算符是否也复制保留空间?
- Qt PL/SQL - 赋值运算符 - 字符串缓冲区太小
- 对 r 值使用移动赋值运算符时的异常
- 由于没有使用赋值运算符,映射的值是如何初始化的?
- 默认赋值运算符如何在实际 STL 中实现
- 具有虚拟赋值运算符的多态性
- C++ 中的纯虚拟赋值运算符
- LNK2019多级类层次结构中的纯虚拟赋值 (=) 运算符
- 未调用派生类的虚拟赋值运算符