gpt4 book ai didi

c++ - 重载 << 运算符,分离实现和声明

转载 作者:行者123 更新时间:2023-11-30 01:16:14 25 4
gpt4 key购买 nike

我正在尝试重载 << 运算符,但出现以下错误。

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

这是我的代码。我将执行和删除分开了。我认为问题的发生是因为我编写的代码与许多网页和 Deitel&Deitel 节目相同。

滚动骰子.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;
}

滚动骰子.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);

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

还要考虑到在运算符定义中您似乎必须使用

int temp=rd.n;

代替

int temp=n;

关于c++ - 重载 << 运算符,分离实现和声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27044694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com