Question

Okay this program is to let some user enter an amount of numbers and it will output them in a straight line with commas in between. I have got every other code to work except for overloading the output operator.

Here's the header file:

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

Here's the cpp file:

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

Any help will be deeply appreciated.

Was it helpful?

Solution

You can use a function similar to this in your class:

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

The overloaded << method of ostream can then be rewritten to this to call the output function:

std::ostream& operator << (std::ostream& out, const ListType& my_list) {
       my_list.output(out);
       return out;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top