假设我有一个继承自 Animal 类的 Dog 类,您可能想在 Dog::operator= 中插入对 Animal::operator= 的调用。
什么是最易读/最常用的写法?
我想我认识这两个...
static_cast<Animal*>(this)->operator=(other);
和
this->Animal::operator=(other);
假设我有一个继承自 Animal 类的 Dog 类,您可能想在 Dog::operator= 中插入对 Animal::operator= 的调用。
什么是最易读/最常用的写法?
我想我认识这两个...
static_cast<Animal*>(this)->operator=(other);
和
this->Animal::operator=(other);
由于您是在子类方法中进行的
Animal::operator=(other);
不需要this->
。范围解析语法完全符合要求。我看不出用演员“间接”做这件事有什么意义。
另请注意,在一般情况下,使用强制转换可能不会产生预期的结果,因为它不会禁用虚拟方法调用的动态解析。(而且,顺便说一句,赋值运算符可以声明为虚拟的)。一个明显的后果是,使用虚拟方法,“cast”变体可能很容易导致无限递归。
this->Animal::operator=(other);
是正确的方法,您完全限定了引用您的父实现的方法,您不需要为此强制转换,这会使代码更难阅读。