1

I'm trying to overload << operator but I get an error which is below.

rollingDice.h|14|error: ‘std::ostream& rollingDice::operator<<(std::ostream&, const rollingDice&)’ must take exactly one argument|

Here is my code. I separated implementation and decleration. I think the problem occurs due to that because I coded same as so many web pages and Deitel&Deitel show.

rollingDice.cpp

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <stdlib.h>
#include "rollingDice.h"
using namespace std;

rollingDice::rollingDice(unsigned int valN)
{
    n=valN;
    r=new int [n];
}
int rollingDice::length()
{
    return n;
}
void rollingDice::generate()
{
    srand48(time(NULL));
    int i=0;
    for (i=0; i<n; ++i)
    {
        r[i]=1+(lrand48()%6);
    }
}
rollingDice& rollingDice::init(unsigned int valN)
{
    n=valN;
    r=new int [n];
    return *this;
}
ostream& operator << (ostream& output, rollingDice& rd)
{
    int temp=n;
    if (temp>12)
        temp=12;
    int i=0;
    for (i=0; i<temp; ++i)
    {
        output << rd.r[i] << " ";
    }
    return output;
}
double rollingDice::getAverage()
{
    generate();
    double total=0;
    int i=0;
    for (i=0; i<n; ++i)
        total+=r[i];
    total=total/double(n);
    return total;
}

rollingDice.h

#ifndef rollingDice_H
#define rollingDice_H
#include <string>
using namespace std;

class rollingDice
{
public:
    rollingDice(unsigned int n);
    void generate();
    rollingDice& init(unsigned int valN);
    double getAverage();
    int length();
    ostream& operator << (ostream& output, const rollingDice& rd);
private:
    unsigned int n;
    int* r;


};

#endif

rollingDiceApp.cpp

#include <iostream>
#include "rollingDice.h"

using namespace std;

int main()
{
    rollingDice r(16);
    cout<<r.getAverage()<<endl;
    cout<<r.length()<<endl;
    r.init(8).generate();
    cout<<r.getAverage()<<endl;
    cout<<r.length()<<endl;
}
  • 1
    Your problem is described here http://stackoverflow.com/questions/4622330/operator-overloading-member-function-vs-non-member-function. You don't want operator << to be a class-member. – Captain Giraffe Nov 20 '14 at 16:32
  • The problem is explained in the error message: when the compiler converts the operator into a function call, it only gives it one argument. But you've declared it with two. It needs to work with the object it was called on. – Mark Ransom Nov 20 '14 at 16:36
  • Then It says "must take exactly two arguments". – Alp Özgüder Nov 20 '14 at 17:50

1 Answers1

5

In the class definition add keyword friend to the operator declaration

friend ostream& operator << (ostream& output, const rollingDice& rd);

Otherwise the compiler consideres the operator as a member function with the first implicit parameter that corresponds to this

Also take into account that in the operator definition it seems you have to use

int temp=rd.n;

instead of

int temp=n;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335