c++ - 如何使这个 operator= 重载工作?
问题描述
我正在尝试使operator=
虚拟化,如下所示:
#include <iostream>
#include <string>
class Base {
public:
std::string field1;
Base(std::string str) : field1(str) {}
virtual Base& operator=(const Base& other)
{
field1 = other.field1;
return *this;
}
};
class Derived : public Base {
public:
std::string field2;
Derived(std::string str1, std::string str2) : Base(str1), field2(str2) {}
virtual Derived& operator=(const Derived& other) override
{
Base::operator=(other);
field2 = other.field2;
return *this;
}
};
但是,这会产生编译器错误,因为该Derived
函数实际上并没有重载任何东西,签名不同。
是否可以覆盖这样的operator=
编写代码?
Base* ptr = new Derived("old 1", "old 2");
Derived derived("new 1", "new 2");
*ptr = derived; // <- use the derived class operator= to assign both field1 and field2
解决方案
该运算符
virtual Derived& operator=(const Derived& other);
不会覆盖基类中声明的复制赋值运算符。
你必须写
Derived& operator=(const Base& other) override;
即参数的类型应为const Base &
。
这是一个演示程序。
#include <iostream>
struct A
{
virtual A & operator =( const A & )
{
std::cout << "A::operator =\n";
return *this;
}
};
struct B : A
{
virtual B & operator =( const A &a ) override
{
A::operator =( a );
std::cout << "B::operator =\n";
return *this;
}
};
int main()
{
B b1;
A &rb1 = b1;
B b2;
b2 = rb1;
return 0;
}
它的输出是
A::operator =
B::operator =
推荐阅读
- authentication - 我在 laravel 中有两个登录重定向条件,无论是同一页面还是仪表板 | 拉拉维尔
- apache-spark - 在 Kubernetes spark-operator 中,Pod 安全上下文不适用于 spark 驱动程序和执行程序
- python - 如何“加入/关联”2个数据帧,以便左侧数据帧的每一行都“附加”到右侧数据帧的每一行
- r - Trace back - find if a string value occurs before another specific string value - dplyr/R
- javascript - React 道具和状态值不更新
- android - 如何解决在 jni 中获取 methodID 的问题
- javascript - 承诺已解决,但代码在等待中停止
- python - 如何搜索对象(或其子对象)是否包含给定名称的字段并验证其值
- string - 如何在绘图功能中使用交替文本字符串
- makefile - 在 Makefile 中,是否总是附加变量 $(CFLAG) ?