【问题标题】:(C++) Invoking base operator from derived class operator(C++) 从派生类运算符调用基运算符
【发布时间】:2014-02-23 01:08:10
【问题描述】:

从派生类的运算符中调用运算符的正确方法是什么?

我试图从派生类的重载运算符中调用基重载运算符。我尝试了以下方法,但似乎不起作用:

const myObject& myObject::operator = (const myObject &otherObject) {
static_cast<BaseType>(*this) = static_cast<BaseType>(otherObject); // assuming BaseType has assignment overloaded
return *this;
}

这是实际代码:

const studentType& studentType::operator = (const studentType &student) {
  static_cast<personType>(*this) = static_cast<personType>(student);

  // new junk here

  return *this;
}

注意:基类的操作符是重载的,所以没有问题。

【问题讨论】:

  • 你的意思可能是overridden 不是overloaded
  • 就我而言,当例程有多个定义时,它被认为是重载,每个定义都有不同的参数。
  • static_cast 方法应该可以工作,但您必须将 reference 强制转换为基本类型,而不是基本类型本身。

标签: c++ polymorphism operator-overloading


【解决方案1】:

使用以下代码

const studentType& studentType::operator = (const studentType &student) {
  personType::operator =(student);

  // new junk here

  return *this;
}

【讨论】:

  • 是的,它起作用了,而且令人惊讶的是,它很有意义,因为 operator= 只是另一个函数/方法/例程。谢谢。
猜你喜欢
  • 2016-07-10
  • 2013-03-03
  • 2021-07-03
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 2012-08-22
  • 2020-11-24
  • 2012-02-12
相关资源
最近更新 更多