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

Pio*_*nom 1 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;
}
Run Code Online (Sandbox Code Playgroud)

和:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

现在,我有一个vector<Item> inventory,我正在添加武器和盾牌.当我遍历库存并cout项目时,我得到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;
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我的问题是为什么它调用基数的运算符重载而不是派生?是否有可能告诉它从派生类中调用它?

R S*_*ahu 5

除了对象切片问题之外,您的代码还会遇到另一个概念问题.您希望operator<<在引用基类时在运行时调用派生类型的函数是没有根据的.这不起作用,因为函数不是多态的.

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

  1. operator<<仅为基类实现该功能.
  2. 具有virtual完成实际工作的成员函数.
  3. virtualoperator<<函数中调用成员函数.

示范代码:

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);
}
Run Code Online (Sandbox Code Playgroud)