c++ - 如何显示从基类派生的对象数组,每个对象都有自己不同的运算符重载函数?
问题描述
所以我有一个基类和 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 - arduino uno上的多个开关盒问题
- python - Python 正则表达式匹配不包含字符串的行
- javascript - 当鼠标移动状态发生变化时反应样式化组件的低性能
- python - 如何使用堆栈实现将此 BFS 代码转换为 DFS 和 UCS..?
- python-3.x - 如何删除列python最小值之前的两行和之后的两行
- google-cloud-platform - 如何在 Google 数据流中加密一个 zipoutputstream
- c# - Unity 的 Mathf.PingPong 实际上做了什么?
- c++ - Char, unsigned char 和signed char as char&
- html - 隐藏的显示属性不适用于段落标签
- typescript - Firebase Cloud Functions - 获取类型错误:无法读取未定义的属性“地图”