Operator Overloading problem with screen insertion operator << - c++

I have overloaded all the operators properly but the relational operators are giving me error while using them with cout . i have tried alot, it gives this error:
[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!='\0';ap++){}
for(;*xp!='\0';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!='\0';ap++){}
for(;*xp!='\0';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
}```

You are not using the ostream& out in the overloaded operators. Try this:
friend ostream &operator<<(ostream &out, GrandInt x) {
out << x.a;
return out;
}
friend istream &operator>>(istream &in, GrandInt x) {
in >> x.a;
return in;
}
And in the main function:
cout<< (num1>num2) << endl; // parenthesis needed because of operator precedence

Related

where's the error and why this program is wrong?

I'm doing an exercise for homework where i have to create a class for a fraction , but when i was coding i got in trouble with the overloading of the operator << ,and i don't understand where's the error because when the program reads the input the two numbers(numerator,denominator) are saved correctly, but when i try to print in output the fraction it gives me a random number; why?
#include <iostream>
using namespace std;
class Frazione{
private:
int num;
int den;
public:
Frazione operator+(Frazione f2){
Frazione risultato;
risultato.den=MCM(f2.den);
risultato.num=(num*(risultato.den/den))+(f2.num*(risultato.den/f2.den));
return risultato;
}
int MCM(int a){
int min;
int k;
if(den>a){
min=a;
}
else{
min=den;
}
for(int i=min;!(den%i==0 && a%min==0);i+=min){
k=i;
}
return k;
}
void setn(int a){
num=a;
}
void setd(int a){
den=a;
}
int getn(){
return num;
}
int getd(){
return den;
}
};
istream& operator>>(istream& in,Frazione f){
int n,d;
cout<<"Dimmi il numeratore"<<endl;
in>>n;
cout<<"Dimmi il denominatore"<<endl;
in>>d;
f.setn(n);
f.setd(d);
return in;
}
ostream& operator<<(ostream& out,Frazione& f){
out<<f.getn();
out<<"/";
out<<f.getd();
return out;
}
int main(){
Frazione f1,f2,f3;
cin>>f1;
cout<<f1;
cin.get();
return 0;
}
Currently don't pay attention to funciont MCM and operator+ because they are function that i have to implement then i'll solve this plobem.
You have missed the reference of the second parameter here:
istream& operator>>(istream& in,Frazione &f)
The parameter f is only accessible by reference.

Overloading issue C++

I seemed to be having an overloading operator issue. I can't really make out what the error is trying to say. Here's the error:
Error: no match for 'operator<<' in
'std::cout << s1.Set::operator+(((const Set&)((const Set*)(& s2))))'
Here's my code:
#include "Set.cpp"
int main(int argc, char *argv[]){
Set s1(10),s2(6),s3(3),s4;
cout<<"First set ({x,y,z}): ";
cin>>s1;
cout<<"A: "<<s1<<endl;
cout<<"Second set: ";
cin>>s2;
cout<<"B: "<<s2<<endl;
cout<<s1+s2<<endl;
}
class Set {
private:
bool elements[255];
int capacity; //Yes, an unsigned char, short, or even size_t, would be better
Set(const bool elements[255], int capacity); //Helpful for immutable types
public:
Set();
Set(short capacity);
friend std::ostream& operator<<(std::ostream &out, Set &set);
friend std::istream& operator>>(std::istream &in, Set &set);
int getCapacity() const; //Cardinality of universe. i.e. |Universe| (or just 'capacity')
};
Set::Set(const bool elements[255], int capacity){
this->capacity = capacity;
for(int i=0; i<255;i++){
if(elements[i] == true && i <= capacity){
this->elements[i] = true;
}
else{
this->elements[i] = false;
}
}
}
Set::Set(short capacity){
this->capacity = capacity;
}
std::ostream& operator<<(std::ostream &out, Set &set) {
int capacity = set.getCapacity();
out<<"{";
for(int i=0; i < 255; i++){
if(set.elements[i] == true ){
out<<i<<",";
}
}
out<<"}";
return out;
}
std::istream& operator>>(std::istream &in, Set &set) {
bool arr[255];
int cap=set.getCapacity();
char open;
in>>open;
if (in.fail() || open!='{') {
in.setstate(std::ios::failbit);
return in;
}
for (int i=0;i<cap;i++)
arr[i]=false;
std::string buff;
std::getline(in,buff,'}');
std::stringstream ss(buff);
std::string field;
while (true) {
std::getline(ss,field,',');
if (ss.fail()) break;
int el;
std::stringstream se(field);
se>>el;
if (el>=0&&el<cap){
arr[el]=true;
}
else{
arr[el]=false;
}
}
set=Set(arr,cap);
}
Set Set::operator+(const Set &other) const{
bool arr[255];
for(int i=0; i<255;i++){
if(this->elements[i] == true || other.elements[i]==true)
arr[i] == true;
}
int capacity = this->capacity>=other.capacity?this->capacity:other.capacity;
return Set(arr,capacity);
}
I overload both the + and >> operators. When executing the code, would it not execute the overloaded + operator first then the >> operator.
Just need some clarification. Thanks
Here's the signature of your overloaded stream insertion operator:
friend std::ostream& operator<<(std::ostream &out, Set &set);
Notice that you're taking your last parameter in as a non-const reference. This means that this function can only take in lvalues as its second parameter. This is fine for all the cases you've listed except this one:
cout << s1+s2 << endl;
I don't believe you included the signature of your operator+ function in your code above, but I'd suspect that it (properly) returns a Set by value. This code gets translated into
(operator<< (cout, s1 + s2)) << endl;
which triggers the issue, since the expression s1 + s2 doesn't evaluate to an lvalue.
To fix this, change the signature of your operator<< function t
friend std::ostream& operator<<(std::ostream &out, const Set &set);
The added const here lets the last parameter bind to anything, including temporaries, which lets you print out s1 + s2 safely. Plus, it (correctly) indicates to the caller that the act of printing out a Set won't actually change that set.
As an aside, it's very weird to include a .cpp file at the top of another .cpp file. You should probably define a header for your Set type and include that. Otherwise, if multiple files try to include the Set.cpp file, you'll get linker errors due to multiple definitions of each of the functions.

C++: Errors while compilation of C++ program

I am making a class Fraction with global functions usage
My code looks like below:
#include<iostream>
using namespace std;
ostream & operator<<(ostream & os, Fraction & fr)
{
return os << fr.get_num() << '/' << fr.get_den();
}
class Fraction
{
private:
int num, den;
public:
int get_num()
{
return num;
}
int get_den()
{
return den;
}
};
Main function has call : `cout << f2 << endl;
But i am getting following build erros while compilation:
Error C2805 binary 'operator <<' has too few parameters
fr: undeclared identifier
left of get_num must be struct/union/class
You should change the order of your code like this:
class Fraction
{
private:
int num, den;
public:
int get_num()
{
return num;
}
int get_den()
{
return den;
}
};
ostream & operator<<(ostream & os, Fraction & fr)
{
return os << fr.get_num() << '/' << fr.get_den();
}

Using vector in C++ to calculate big integer

I've coded a program to practice using header and class.
So the project have three files.
main.cpp BigInteger.h BigInteger.cpp
I called class "BigInteger" in main.cpp
when I read the string from main,it shows correctly.
But when I using +,-,* operator.
It shows me the answer but add a '0' in front of the answer.
the following is my code
//main.cpp
#include "BigInteger.h"
int main() {
BigInteger a("-1234567890");
BigInteger b("234567891");
BigInteger ans1, ans2, ans3, ans4;
BigInteger c(a), d;
ans1 = a + b;
ans2 = a - c;
ans3 = c - b;
ans4 = a*b;
cout<<"a="; a.print();
cout<<"b="; b.print();
cout<<"c="; c.print();
cout<<"d="; d.print();
cout<<"a+b="; ans1.print();
cout<<"a-c="; ans2.print();
cout<<"c-b="; ans3.print();
cout<<"a*b="; ans4.print();
}
//header
#include <iostream>
#include <vector>
#include <string>
#define MAX_SIZE 80
using namespace std;
static const int ROWS=4, COLS=4;
class BigInteger{
private:
vector <int> digits;
bool positive; //正負數,0的正負設為正
void adding(const vector <int> &x,const vector <int> &y, vector <int> &z);
void subing(const vector <int> &x ,const vector <int> &y, vector <int> &z);
bool max(const vector <int> & x,const vector <int> & y);
void Reverse( vector <int> & r);
public:
BigInteger(string s);
BigInteger();
BigInteger(const BigInteger & r);
BigInteger & operator =(const BigInteger & r);
BigInteger operator +(const BigInteger & r);
BigInteger operator -(const BigInteger & r);
BigInteger operator *(const BigInteger & r);
void print();
};
//BigInteger.cpp
#include "BigInteger.h"
#include "math.h"
BigInteger::BigInteger(string s)
{
for(int i=0;i<s.size();i++) {
if(s[i]!='-') {
digits.push_back(s[i]-'0');
}
}
if(s[0]=='-') positive=true;
else positive=false;
}
BigInteger::BigInteger()
{
digits.push_back(0);
positive=false;
}
BigInteger::BigInteger(const BigInteger & x){
for(int i=0;i<x.digits.size();i++)
digits.push_back(x.digits[i]);
positive=x.positive;
}
BigInteger & BigInteger::operator =(const BigInteger & x){
for(int i=0;i<x.digits.size();i++)
digits.push_back(x.digits[i]);
positive=x.positive;
return (*this);
}
BigInteger BigInteger::operator +(const BigInteger & x){
BigInteger answer;
answer.digits.clear();
bool pre; //if the front one is bigger return true.
if(positive==x.positive){
answer.positive=positive;
adding(digits,x.digits,answer.digits);
}
else{
pre=max(digits,x.digits);
if(pre) subing(digits,x.digits,answer.digits);
else subing(x.digits,digits,answer.digits);
answer.positive=false;
if(positive&&pre) answer.positive=true;
if((!positive)&&(!pre)) answer.positive=true;
}
return answer;
}
BigInteger BigInteger::operator -(const BigInteger & x){
BigInteger answer;
answer.digits.clear();
bool pre=max(digits,x.digits);
if(positive!=x.positive){
answer.positive=true;
if(pre) adding(digits,x.digits,answer.digits);
else adding(x.digits,digits,answer.digits);
}
else if(positive&&x.positive){
if(pre) {
subing(digits,x.digits,answer.digits);
answer.positive=true;}
else {
subing(x.digits,digits,answer.digits);
answer.positive=false;}
}
else {
if(pre){
answer.positive=false;
subing(digits,x.digits,answer.digits);}
else {
answer.positive=true;
subing(x.digits,digits,answer.digits);
}
}
return answer;
}
BigInteger BigInteger::operator *(const BigInteger & x){
BigInteger answer;
long long int a=0,b=0,ans=0;
int ten=1;
answer.digits.clear();
for(int i=digits.size()-1;i>=0;i--)
{
a+=digits[i]*ten;
ten*=10;
}
ten=1;
for(int i=x.digits.size()-1;i>=0;i--)
{
b+=x.digits[i]*ten;
ten*=10;
}
ans=a*b;
if(positive==x.positive) answer.positive=false;
else answer.positive=true;
while(ans>0)
{
answer.digits.push_back(ans%10);
ans=ans/10;
}
Reverse(answer.digits); //cause i use push_back ,it will be backwards
return answer;
}
void BigInteger::adding(const vector <int> & x,const vector <int> & y, vector <int> & z)
{
long long int a=0,b=0,ans=0;
BigInteger answer;
int ten=1;
answer.digits.clear();
for(int i=x.size()-1;i>=0;i--)
{
a+=x[i]*ten;
ten*=10;
}
ten=1;
for(int i=y.size()-1;i>=0;i--)
{
b+=y[i]*ten;
ten*=10;
}
ans=a+b;
while(ans>0)
{
z.push_back(ans%10);
ans=ans/10;
}
Reverse(z); //cause i use push_back ,it will be backwards
}
void BigInteger::subing(const vector <int> & x,const vector <int> & y, vector <int> & z){
long long int a=0,b=0,ans=0;
BigInteger answer;
int ten=1;
answer.digits.clear();
for(int i=x.size()-1;i>=0;i--)
{
a+=x[i]*ten;
ten*=10;
}
ten=1;
for(int i=y.size()-1;i>=0;i--)
{
b+=y[i]*ten;
ten*=10;
}
ans=a-b;
while(ans>0){
z.push_back(ans%10);
ans/=10;
}
Reverse(z); //cause i use push_back ,it will be backwards
}
bool BigInteger::max(const vector <int> & x,const vector <int> & y){
if(x.size()>y.size())
return true;
else return false;
}
void BigInteger::Reverse(vector <int> & z) {
int temp,j=z.size()-1;
for(int i=0;i<z.size()/2;i++)
{
temp=z[i];
z[i]=z[j];
z[j]=temp;
j-=1;
}
}
void BigInteger::print()
{
if(positive==true)
cout<<"-";
else
cout<<"";
//cout<<digits[0]<<endl;
for(int i=0;i<digits.size();i++){
cout<<digits[i];
}
cout<<endl;
// cout<<digits[6]<<digits[7]<<digits[8]<<digits[9]<<endl;
}
void BigInteger::print()
{
if(positive==true)
cout<<"-";
else
cout<<"";
//cout<<digits[0]<<endl;
for(int i=0;i<digits.size();i++){
cout<<digits[i];
}
cout<<endl;
// cout<<digits[6]<<digits[7]<<digits[8]<<digits[9]<<endl;
}
You can write like this
void BigInteger::print()
{
if(positive==true)
cout<<"-";
else
cout<<"";
//cout<<digits[0]<<endl;
bool not_zero_detect=false;
for(int i=0;i<digits.size();i++){
if(digits.size()!=1&& digits[i]==0 && not_zero_detect==false)
{
digits[i]=digits[i];
}
else
{
not_zero_detect=true;
cout<<digits[i];
}
}
cout<<endl;
// cout<<digits[6]<<digits[7]<<digits[8]<<digits[9]<<endl;
}
use bool like "not_zero_detect" to check whether it has zero in front of the number or not
PS: Thanks for sharing your homework :-)

error: overloaded 'operator<<' must be a binary operator (has 3 parameters)

I know there are plenty of questions like these, but I couldn't find a solution that worked for me.
I am trying to make simple fraction calculator than can add or subtract any number of functions and write the answer as a reduced fraction.
Example: input=
3/2 + 4/
8
, output =
2
I am trying overload operators in order to accomplish this.
So in the program I am trying to develop, the input consists of an expression made of fractions separated by the operators + or -.
The number of fractions in the expression is arbitrary.
Each of the following 6 lines is an example of a valid input expression:
1/2 + 3/4
1/2 -5/7+3/5
355/113
3 /9-21/ -7
4/7-5/-8
-2/-3+7/5
***The problem that I am having is that in when I run my program it has an overload operating error: *error: overloaded 'operator<<' must be a binary operator (has 3 parameters)****
/Users/Spicycurryman/Desktop/ECS40/hw1/fraction.cpp:61:22: error: overloaded 'operator<<' must be a binary operator (has 3 parameters)
ostream& Fraction::operator<<(ostream &os, Fraction& n)
^
/Users/Spicycurryman/Desktop/ECS40/hw1/fraction.cpp:80:22: error: overloaded 'operator>>' must be a binary operator (has 3 parameters)
istream& Fraction::operator>>(istream &os, Fraction& n)
I don't understand why that is an error.
My following code is below:
CPP FILE
#include "Fraction.h"
Fraction::Fraction(int a, int b)
{
}
int Fraction::find_gcd (int n1, int n2)
{
int gcd, remainder;
remainder = n1 % n2;
while ( remainder != 0 )
{
n1 = n2;
n2 = remainder;
remainder = n1 % n2;
}
gcd = n2;
return (gcd);
}
void Fraction::reduce_fraction(int nump, int denomp)
{
this->nump = nump;
this->denomp = denomp;
int gcd;
gcd = find_gcd(nump, denomp);
nump = nump / gcd;
denomp = denomp / gcd;
if ((denomp<0 && nump < 0 ))
{
denomp*=-1;
nump*=-1;
}
else if (denomp < 0 && nump >0){
denomp*=-1;
}
if ( denomp ==0) {
throw invalid_argument( "Error: zero denominator" );
}
}
Fraction& Fraction::operator+(const Fraction& n) {
denom = denomp * n.denom;
numera = (nump * n.numera) + (n.denom * n.nump);
return (*this);
}
Fraction& Fraction::operator-(const Fraction& n) {
denom = denomp * n.denom;
numera = (nump * n.numera) - (n.denom* n.nump);
return (*this);
}
ostream& Fraction::operator<<(ostream &os, Fraction& n)
{
if (n.numera == 0)
{
cout << 0 << endl;
return os;
}
else if (n.numera == n.denom)
{
cout << 1 << endl;
return os;
}
else
{
cout << n.numera << '/' << n.denom << endl;
return os;
}
}
istream& Fraction::operator>>(istream &os, Fraction& n)
{
char slash = 0;
return os >> n.numera >> slash >> n.denom;
}
Header File
#ifndef FRACTION_H
#define FRACTION_H
#include <iostream>
#include <stdexcept>
using namespace std;
class Fraction{
public:
Fraction(int a, int b);
int fraction(int a,int b);
int find_gcd(int n1, int n2);
void reduce_fraction(int nump, int denomp);
Fraction& operator+(const Fraction& n);
Fraction& operator-(const Fraction& n);
friend ostream& operator<<(ostream &os, const Fraction& n);
friend istream& operator>>(istream &is, const Fraction& n);
private:
int denom;
int numera;
int denomp;
int nump;
};
#endif
MAIN CPP FILE
#include "Fraction.h"
#include <iostream>
using namespace std;
int main()
{
Fraction x(2,3);
Fraction y(6,-2);
cout << x << endl;
cout << y << endl;
cin >> y;
cout << y << endl;
Fraction z = x + y;
cout << x << " + " << y << " = " << z << endl;
}
I know that the operators are member functions and a member function takes an implicit first parameter, meaning my operators now takes three parameters it may be fixed being a non-member function; however, that would not work in this program. How exactly in my case would I fix it so the program would work?
Thank you very much!
The problem is that you declared operator>> and operator<< as non-member functions, but defined as a member function.
This should fix that problem (but open another set of problems). So instead of
ostream& Fraction::operator<<(ostream &os, Fraction& n)
{
...
istream& Fraction::operator>>(istream &os, Fraction& n)
{
...
implement as :
ostream& operator<<(ostream &os, Fraction& n)
{
...
istream& operator>>(istream &os, Fraction& n)
{
...
Also, take a note that you declared functions as :
friend ostream& operator<<(ostream &os, const Fraction& n);
friend istream& operator>>(istream &is, const Fraction& n);
but defined as (therefore you changed the signature) :
ostream& Fraction::operator<<(ostream &os, Fraction& n)
istream& Fraction::operator>>(istream &os, Fraction& n)
Proper way is to declare and define as :
ostream& Fraction::operator<<(ostream &os, const Fraction& n)
istream& Fraction::operator>>(istream &os, Fraction& n)
I am adding just changes. The rest is the same as in the question:
class Fraction{
friend ostream& operator<<(ostream &os, const Fraction& n);
friend istream& operator>>(istream &is, Fraction& n);
// the rest is the same
};
ostream& operator<<(ostream &os, const Fraction& n)
{
if (n.numera == 0)
{
cout << 0 << endl;
return os;
}
else if (n.numera == n.denom)
{
cout << 1 << endl;
return os;
}
else
{
cout << n.numera << '/' << n.denom << endl;
return os;
}
}
istream& operator>>(istream &os, Fraction& n)
{
char slash = 0;
return os >> n.numera >> slash >> n.denom;
}