簡體   English   中英

重載<<運算符,實現和分離

[英]Overloading << operator, separated implementation and decleration

我正在嘗試重載<<運算符,但出現以下錯誤。

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

這是我的代碼。 我將實現與執行分開。 我認為出現此問題是因為我編碼的代碼與許多網頁和Deitel&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;
}

在類定義中,將關鍵字friend添加到運算符聲明中

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

否則編譯器consideres操作者與對應於所述第一隱式參數的成員函數this

還應考慮到在運算符定義中似乎必須使用

int temp=rd.n;

代替

int temp=n;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM