c++ operator =重载继承,是否需要在派生类中重新定义,尽管在基类中定义
C++ operator = overload inherited, is it necessary to redefine in the derived class though defined in the base class?
假设我有这样的c++代码:
class Base {
public:
Base& operator=(const Base&);
};
class Derivate : public Base {
public:
};
我有一个main where
Derivate d1;
//Something on d1
Derivate d2 = d1;
在这种情况下,基类的操作符=
会调用吗?我有一些代码,基本上做这样的事情,但调试与gdb我没有看到任何调用这样的操作符。
在这种情况下,有必要在派生类中重新定义操作符吗?
不,实际上你是在调用复制构造函数,因为你在构造d2的同时将d1赋值给d2,因此这里没有调用赋值操作符:
#include <iostream>
using namespace std;
class Base
{
public:
Base& operator = (const Base&);
};
Base& Base::operator = (const Base&)
{
cout << "assignment operator" << endl;
// implementation here
return *this;
}
class Derivate : public Base
{
public:
Derivate(){}
Derivate(const Derivate& rhs){cout << "copy constructor" << endl;}
};
int main()
{
Derivate d1;
//Something on d1
Derivate d2 = d1; // copy constructor not assignment operstor
//Derivate d2(d1); // is the same as above calling cpy ctor
d2 = d1; // here assignment operator is called
return 0;
}
- 为什么
d2 = d1;
调用基赋值操作符?
,因为如果你不提供派生类的赋值操作符,编译器会为你定义一个,如下所示:
Derivate& operator = (const Base& rhs); // not Derivate
因此,只要传递const引用而不是派生引用,派生类就会调用基类的赋值操作符。
- 赋值操作符实际上是继承的:
在基类中设置私有作用域并查看结果
相关文章:
- 如何定义一个纯抽象基类
- 使用子类覆盖基类中定义的函数
- 将抽象基类中的所有纯虚函数定义为 varaidaic 模板
- 使(虚拟)函数在大多数派生类中无法访问中间基类中可访问,定义良好?
- 为什么为派生类定义复制构造函数需要定义基类的默认构造函数?
- Linux c++.在预加载的共享库中定义的基类的崩溃调用函数
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- 错误:基类在从基类父派生类 Son 时未定义
- 无法使用在子类中定义的虚拟getter实现基类
- 从派生类重新定义基类中定义的结构
- 在派生类中重新定义基类的友元函数
- 继承基类,定义基类的原型方法,但从第三个对象调用子类的方法
- C++:如何在派生类中定义基类构造函数,如果基构造函数具有带有私有成员的初始化列表
- 'class'类型重定义/基类未定义
- 使用派生类成员的地址定义基类成员指针
- 派生类是否可以在类声明中定义基类数组的大小
- 错误 C2504:'ostream_withassign':未定义基类
- 关于c++中的继承,派生类是否可以在不显式定义基类的情况下从基类获得实现
- 定义基类的静态变量
- 错误 C2504:"自动售货机":未定义基类