抽象类和重载Ouput运算符

Abstract Classes and Overloading Ouput Operator

本文关键字:运算符 Ouput 重载 抽象类      更新时间:2023-10-16

好的,这个程序让一些用户输入一定数量的数字,并将它们输出为一条带逗号的直线。除了重载输出运算符之外,我还有其他所有代码可以工作。

这是头文件:

#ifndef LISTTYPE_H_INCLUDED
#define LISTTYPE_H_INCLUDED
#include <iostream>
class ListType {
public:
 ListType(size_t=10);
 virtual ~ListType();
 virtual bool insert(int)=0;
 virtual bool erase();
 virtual bool erase(int)=0;
 virtual bool find(int) const=0;
 size_t size() const;
 bool empty() const;
 bool full() const;
 friend std::ostream& operator << (std::ostream&, const ListType&);
protected:
 int *items;
 size_t capacity;
 size_t count;
};

这是cpp文件:

#include "ListType.h"
ListType::ListType (size_t a) {
 capacity = a;
 count = 0;
 items = new int [capacity];
}
ListType::~ListType() {
 delete [] items;
}
bool ListType::erase() {
 count = 0;
 return 0;
}
size_t ListType::size() const {
 return (count);
}
bool ListType::empty() const {
 return (count == 0);
}
bool ListType::full() const {
 return (count == capacity);
}
std::ostream& operator << (std::ostream& out, const ListType& list1) {
 int a = 0;
 out << list1[a] << ", " ;
 return out;
}

任何帮助都将不胜感激。

您可以在类中使用类似的函数:

void ListType::output(std::ostream& out) const {
    for (int i = 0; i < count; i++) {
          if (i > 0) { // No comma for first element
                   out << ", ";
          }
          out << items[i];
    }
}

然后可以将ostream的重载<<方法重写为该方法,以调用输出函数:

std::ostream& operator << (std::ostream& out, const ListType& my_list) {
       my_list.output(out);
       return out;
}