0

I really need some help. My << operator in my class does not work, but i don't know why. I get errors like: "function text skipped" and "too many parameters". The Print()-function works. But the operator << is the problem.

int main(){

    Set<int> s;
    s.Add(1);
    s.Add(9);
    cout << s;

}



template <typename T>
class Set {
public:

    //Hinzufügen eines Elements
    bool Add(T const &x) { return mSet.insert(x).second; }

    //Entfernen eines Elements
    bool Remove(T const &x) { return mSet.erase(x) > 0; }

    //Prüfen, ob Wert enthalten ist
    bool Contains(T const &x) { return mSet.count(x) > 0; }


    //Ausgabe auf einen Stream
    void Print(std::ostream &out) const{
        std::for_each(mSet.begin(), mSet.end(), [&out](const T elem) { out << elem << "\n"; });
    }

    //ruft einfach Print auf
    std::ostream& operator<<(std::ostream& out, const Set<T> & obj)
    {
        obj.Print(out);
        return out;
    }

private:
    std::set<T> mSet;

};

Is anyone able to fix the problem? I'm really despairing...

  • it should be a `friend` function if it's inside a class – Piotr Skotnicki Dec 02 '15 at 18:03
  • Make `std::ostream& operator<<(std::ostream& out, const Set & obj)` a freestanding function (It is useless inside the class declaration, unless you declare it as friend - which is not needed here) –  Dec 02 '15 at 18:04
  • if you decide the `operator<<` should stay inside class `Set`, then it should be declared as `friend std::ostream& operator<<(std::ostream& out, const Set & obj) { /**/ }` – Piotr Skotnicki Dec 02 '15 at 18:06
  • 1
    Thanks a lot. Both versions work. The friend-version and the freestanding version of the operator. A bif thank you! Honestly! – Magdalena Lauberger Dec 02 '15 at 18:10

0 Answers0