c++ - 在基类和派生类中重载运算符

标签 c++

<分区>

我有一个基类 Item 和派生类 Weapon & Shield。两者都重载<<。

// item(base) operator overload
ostream& operator<<(ostream& os, const Item& a_item)
{
    os << "     Item Object - " << endl;
    os << "          Name: " << a_item.m_name << endl;
    os << "          Cost: " << a_item.m_cost << endl;
    os << "          Purpose: " << a_item.m_purpose << endl;

    return os;
}

和:

// weapon(derived) operator overload
ostream & operator<<(ostream & os, const Weapon & a_weapon)
{
    os << "Weapon - " << endl;
    os << "     Name: " << a_weapon.m_name << endl;
    os << "     Cost: " << a_weapon.m_cost << endl;
    os << "     Purpose: " << a_weapon.m_purpose << endl;

    return os;
}

// shield(derived) operator overload
ostream & operator<<(ostream & os, const Shield & a_shield)
{
    os << "Shield - " << endl;
    os << "     Name: " << a_shield.m_name << endl;
    os << "     Cost: " << a_shield.m_cost << endl;
    os << "     Purpose: " << a_shield.m_purpose << endl;

    return os;
}

现在,我有一个 vector<Item> inventory ,我正在向其中添加武器和盾牌。当我遍历库存并计算项目时,我得到了 Item 运算符而不是该特定项目的运算符。这是我调用 cout 的方式:

// person(derived) operator overload
ostream& operator<<(ostream& os, const Person& a_person)
{
    os << "Person Object - " << endl;
    os << "     Name: " << a_person.m_name << endl;
    os << "     Level: " << a_person.m_level << endl;
    os << "     Hit Points: " << a_person.m_hit_points << endl;
    os << "     Inventory: " << endl;

    for (auto i = 0; i < a_person.m_inventory.size(); i++)
    {
        os << "     " << a_person.m_inventory[i] << endl;
    }

    return os;
}

enter image description here

我的问题是为什么它调用基类的运算符重载,而不是派生类?是否可以告诉它调用派生类中的那个?

最佳答案

除了object slicing problem ,您的代码存在另一个概念性问题。您对 operator<< 的期望当您对基类的引用没有根据时,将在运行时调用派生类型的函数。这是行不通的,因为函数不是多态的。

你必须稍微改变一下策略,让它们像多态函数一样工作。

  1. 实现 operator<<仅对基类起作用。
  2. virtual执行实际工作的成员函数。
  3. 调用 virtual来自 operator<< 的成员函数功能。

演示代码:

struct Base
{
   virtual std::ostream& print(std::ostream& os) const
   {
      // Print base class details

      return os;
   }
};

struct Derived : Base
{
   virtual std::ostream& print(std::ostream& os) const
   {
      // Do the base class printing first
      Base::print(os);

      // Print the derived class details.

      return os;
   }
};

std::ostream& operator<<(std::ostream& os, Base const& b)
{
   // This will be a polymorphic call.
   return b.print(os);
}

关于c++ - 在基类和派生类中重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50940869/

相关文章:

c++ - 派生内部类的成员

c++ - 从 char 数组中剥离字符作为 C++ 中的指针传递

c++ - 通过已经存在的对象初始化一个动态分配的对象

C++ : Starting a timer from a certain timestamp, 并递增它

c++ - 我可以方便地将 QVariant 转换回 QList<MyType> 吗?

c++ - 如何使用新的 c++0x regex 对象在字符串中重复匹配?

c++ - 如何创建一个可以向其传递函数或仿函数的方法?

c++ - 类定义中的无作用域枚举数

c++ - SIMD/SSE : short dot product and short max value

c++ - 创建安装包是否代替编译代码?