重载<<运营商,分开执行和声明

时间:2014-11-20 16:31:15

标签: c++ operator-overloading

我正在尝试重载<<运算符,但我得到一个错误,低于。

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

这是我的代码。我将执行和删除分开了。我认为问题的出现是因为我的编码和很多网页和Deitel&amp; Deitel一样。

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 个答案:

答案 0 :(得分:5)

在类定义中,将关键字friend添加到运算符声明

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

否则编译器会将运算符视为成员函数,其第一个隐式参数对应于this

还要考虑到在运营商定义中,您似乎必须使用

int temp=rd.n;

而不是

int temp=n;