使用指向基类的指针在派生类中重载c++运算符

c++ Operator overloading in derivated class using pointers to base class

本文关键字:派生 重载 运算符 c++ 指针 基类      更新时间:2023-10-16

我正在用c++为一个嵌入式系统编写一个,它的行为类似于多种类型的变量(int、float、string等)。通过处理每种类型的值的子类。我需要对一些运算符执行运算符重载,例如(+-*/=!=+=-===><&||!)但是执行从指针到基类的操作。我应该如何编写这些函数?我正在测试这样的东西,但它不能求和。

class base
{ 
public:
virtual base& operator=(const base& other) {};
virtual base& operator+(const base& other) {};
...
}
class VarInt: public base
{
public:
int value;
VarInt& operator=(const VarInt& other);
VarInt& operator+(const VarInt& other);
}
class VarFloat : public base
{
public:
float value;
...
}
main(){
...
base* varbase1 = new VarInt();
base* varbase2 = new VarInt();
*varbase1 = 1;
*varbase2 = 2;
*varbase1 += *varbase2;
}

您的问题在于假设当VarIntbase继承时,则:

virtual base& operator = (const base& other) {};

virtual VarInt& operator = (const VarInt& other) {};

是完全一样的东西。不幸的是,它们不是。你在这里所做的是隐藏以前的方法。当您override一个虚拟函数时,您需要以与首次声明完全相同的方式指定它,即:

virtual base& operator = (const base& other) {};

返回的base&可以绑定到VarInt对象,所以我们在这里是安全的。所提供的参数const base&也可以引用到VarInt对象。现在你必须思考你在这里真正想要实现什么。假设从base类可以继承多个具有不同功能的类,例如,如果尝试将VarFloat添加到VarInt,会发生什么?预期结果是什么?编译器错误?引发异常?

如果您真的希望使operator =能够处理继承类的所有排列,那么使用dynamic_cast<>static_cast<>就可以了——请记住,如果您碰巧需要使用强制转换,您可能希望重新考虑您的设计。不建议使用它们。

有关...cast用法的工作示例,请参阅此处:

class Base{
public:
// mandatory for destructing the objects via pointer of a base class
virtual ~Base() = default;
virtual Base& operator = (const Base& other) {};
};
class VarInt : public Base{
public:
virtual Base& operator = (const Base& other) override
{
const auto ptr = dynamic_cast<const VarInt*>(&other);
if(ptr != nullptr){
// do whatever you need to - the *other* object is of a type VarInt!
// use *ptr* to use *other* as VarInt
return *this;
} else {
// do whatever you need to, when *other* is NOT a VarInt!
// throw an exception? Add nothing?
}
}
};

请记住,不建议日常使用-铸造是设计缺陷的标志,不应首选