抽象类和重载输出运算符

时间:2013-12-11 00:44:09

标签: c++ operator-overloading abstract-class pure-virtual

好的,这个程序是让一些用户输入一定数量的数字,然后用直线输出它们之间的逗号。除了重载输出操作符之外,我还有其他所有代码都可以工作。

这是头文件:

#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;
}

任何帮助都将深受赞赏。

1 个答案:

答案 0 :(得分:0)

您可以在班级中使用与此类似的功能:

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;
}