首页 > 解决方案 > 如何显示从基类派生的对象数组,每个对象都有自己不同的运算符重载函数?

问题描述

所以我有一个基类和 3 个派生类,另一个类模板作为参数被赋予基类,类模板有一个由 3 种不同类型的对象组成的数组。我已经为所有 3 个派生类和基类重载了 << 运算符,但是当我尝试在控制台中显示所有数组时,使用了基类运算符重载函数,我该如何做到我遍历对象数组并显示每个对象,每种类型的对象都不同吗?

基类表示

#pragma once
#include <iostream>
#include <string>
class Sushi
{
private:
    static int count;
protected:
    int id;
    int cost;
    std::string fish_type;
public:
    Sushi();
    Sushi(int cost, std::string fish_type);
    ~Sushi();

    int get_id();
    int get_cost();
    std::string get_ftype();

    void set_cost(int cost);
    void set_ftype(std::string fish);
    friend std::ostream& operator<<(std::ostream& os, const Sushi& sushi);
};

基类运算符

std::ostream& operator<<(std::ostream& os, const Sushi& sushi)
{
    os << sushi.id << " " << sushi.cost << " " << sushi.fish_type << std::endl;
    return os;
}

类模板表示

#pragma once
#include "Sushi.h"
template <class Sushi>
class SushiRepository
{
    Sushi *repo;
    int capacity;
    int top;

public:
    //default constructor
    SushiRepository();
    
    //constructor
    SushiRepository(int size);

    //adds an element to top of the stack
    void push(Sushi s);

    //Pops an element from the top of the stack and returns it
    Sushi pop();

    //Returns the last element from the top of the stack
    Sushi peek();

    //returns the size of the repo
    int size();

    //checks if repo is empty
    bool isEmpty();

    //checks if repo is full
    bool isFull();

    //remove by id
    void removeByID(int id);

    //display all
    void displayAll();

    ~SushiRepository();
};

类模板展示功能

template <class Sushi>
inline void SushiRepository<Sushi>::displayAll()
{
    if (!isEmpty()) {
        for (int i = 0; i < size(); i++)
        {
            std::cout << repo[i] << std::endl;
        }
    }
    else {
        std::cout << "Repo is empty";
    }
}

template<class Sushi>
SushiRepository<Sushi>::~SushiRepository()
{
    delete[] repo;
}

派生类表示

#pragma once
#include "Sushi.h"
#include <ostream>
class Sashimi : public Sushi
{
    std::string bed;

public:
    Sashimi();
    Sashimi(std::string bed);
    ~Sashimi();

    std::string get_bed();
    void set_bed(std::string b);
    friend std::ostream &operator<<(std::ostream &os, const Sashimi &sh);
};

派生类运算符重载函数之一

std::ostream& operator<<(std::ostream& os, const Sashimi& sh)
{
    os << "ID:" << sh.id << " Sashimi of " << sh.fish_type << " on a bed of: " << sh.bed << " cost: " << sh.cost << std::endl;
    return os;
}

标签: c++classoperator-overloading

解决方案


推荐阅读