屏幕插入运算符<<的运算符过载问题

Operator Overloading problem with screen insertion operator <<

本文关键字:lt 运算符 问题 屏幕 插入      更新时间:2023-10-16

我已经正确地重载了所有运算符,但是关系运算符在将它们与cout一起使用时给了我错误。 我已经尝试了很多,它给出了这个错误:

[Error] no match for 'operator<<' (operand types are 'GrandInt' and '<unresolved overloaded function type>')

#include <iostream>
#include<string.h>
using namespace std;
class GrandInt{
string a;
public:
GrandInt(){
a="";
}
GrandInt(long long unsigned int n){
a=to_string(n);
}
GrandInt(string n){
a=n;
}
GrandInt(const GrandInt &x){
a=x.a;
}
GrandInt operator+(GrandInt &x){
char *ap= new char [a.length()+1];
int al=a.length();
strcpy(ap,a.c_str());
char *xp= new char [x.a.length()+1];
int xl=x.a.length();
strcpy(xp,x.a.c_str());
for(;*ap!='';ap++){}
for(;*xp!='';xp++){}
int rl;
if(xl>al)
rl=xl+1;
else
rl=al+1;
char *r=new char [rl+1];
ap--;xp--;
int ac,xc,sum,cary=0,c=0;
for(;al>=0||xl>=0;al--,xl--,ap--,xp--,r++,c++){
if(al>0)
ac=*ap-48;
else
ac=0;
if(xl>0)
xc=*xp-48;
else
xc=0;
sum=ac+xc+cary;
if(sum>9){
cary=sum/10;
sum=sum%10;
}
else
cary=0;
*r=sum+48;
}
r--;
if(*r=='0')
{   r--;c--;}
GrandInt temp;
for(;c>0;c--,r--){
temp.a=temp.a+*r;
}
return temp;
}
GrandInt operator-(GrandInt &x){
char *ap= new char [a.length()+1];
int al=a.length();
strcpy(ap,a.c_str());
char *xp= new char [x.a.length()+1];
int xl=x.a.length();
strcpy(xp,x.a.c_str());
for(;*ap!='';ap++){}
for(;*xp!='';xp++){}
int rl=al;
char *r=new char [rl+1];
ap--;xp--;
int ac,xc,sum,cary=0,c=0;
for(;al>=0||xl>=0;al--,xl--,ap--,xp--,r++,c++){
if(xl>0)
xc=*xp-48;
else
xc=0;
ac=*ap-48;
if(ac<xc){
cary=10;
ap--;
*ap=*ap-1;
ap++;
}
sum=ac-xc+cary;
*r=sum+48;
cary=0;
}
r--;
if(*r=='0')
{   r--;c--;}
GrandInt temp;
for(;c>0;c--,r--){
temp.a=temp.a+*r;
}
return temp;
}
bool operator>(GrandInt &x){
if(a.compare(x.a)>0)
return 0;
else
return 1;
}
friend ostream &operator <<(ostream &out,GrandInt x){
cout<<x.a;
return out;
}
friend istream &operator>>(istream &in, GrandInt x){
cin>>x.a;
return in;
}
};
int main()
{
//starting with small numbers
GrandInt num1("546");
GrandInt num2("60");
cout<<num1+num2<<endl;//606
cout<<num1-num2<<endl;//486
cout<<num1>num2<<endl;//1
}```

您没有在重载运算符中使用ostream& out。试试这个:

friend ostream &operator<<(ostream &out, GrandInt x) {
out << x.a;
return out;
}
friend istream &operator>>(istream &in, GrandInt x) {
in >> x.a;
return in;
}

在主功能中:

cout<< (num1>num2) << endl; // parenthesis needed because of operator precedence