使用指向基类的指针在派生类中重载c++运算符
c++ Operator overloading in derivated class using pointers to base class
我正在用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;
}
您的问题在于假设当VarInt
从base
继承时,则:
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?
}
}
};
请记住,不建议日常使用-铸造是设计缺陷的标志,不应首选
相关文章:
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- C++派生类重载函数(带有 std::function 参数)不可见
- 从多个模板化基类派生时出现"隐藏重载的虚函数"警告
- 将基类的成员函数重载到其他派生类C++
- 如何从派生类访问基类中的重载运算符?
- C++ 继承:基类中重载 operator+ 的 2 次在派生类中无法正常工作
- 如何调用继承的重载运算符<<并在派生类的输出中添加更多文本?
- 派生类中的重载运算符
- 派生类不能用另一个基类的成员重载基类中的私有成员
- 指向派生类的指针的重载解析
- 基类和派生类的虚拟插入运算符重载
- 基类和派生类中的模板成员之间的重载解析
- 派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
- 使用派生类进行函数重载
- 派生 std::ofstream 和重载运算符<<
- C++:使用重载而不是动态强制转换通过基选择派生类
- 从派生类调用重载函数
- 如何从派生类实例调用父类重载函数
- 重载输入 重载输入派生类中的基类