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

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.

Related

Operator Overloading problem with screen insertion operator <<

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

Arithmatic operator overloading in c++

#include<iostream>
using namespace std;
class money
{
int rs;
int p;
public:
void setdata (int x , int y)
{rs=x; p=y;}
void show()
{ cout <<rs <<"." <<p; }
money operator += (int a) {
money temp;
temp.rs=rs+a.rs;
temp.p=p+a.p;
return (temp);
}
};
int main() {
money c1,c2;
c1.setdata(8,2);
c2=c1.operator+=(4);
c2.show();
}
Can someone tell me why the operator += overloading doesn't work?
My desiring output is 12.2 but the output i got is 16.2 .
I am sending 4 as argument and i want this argument is added in r (ruppee)
part
#include<iostream>
using namespace std;
class money
{
int rs;
int p;
public:
void setdata (int x , int y)
{rs=x; p=y;}
void show()
{ cout <<rs <<"." <<p; }
money& operator+=(int a)
{ rs += a; return *this; }
};
int main() {
money c1,c2;
c1.setdata(4,2);
c2=c1+=(4); //c2=c1.operator+=(4);
c2.show();
}
Try to use constructor correctly.
For example:
#include <iostream>
using namespace std;
class Example
{
public:
int x;
Example(int a)
{
x=a;
}
Example operator+(Example obj)
{
Example ans(0);
ans=x+obj.x;
return ans;
}
};
int main()
{
Example a(10),b(20);
Example ans=a+b;
cout<<ans.x<<endl;
return 0;
}

Process exited with value 3221225477

I created a program that use a dynamic array. It works, when i use my insert function and then i show the elements of the arrays, it show me all what i want. The problem is that at the end of the program it doesn't return with value 0, but it is blocked for a few second and say "Process exited with value 3221225477". What is wrong?
header:
#ifndef VETTORE_H
#define VETTORE_H
#include "regalo.h"
typedef regalo T;
class vettore {
friend ostream& operator<<(ostream&,const vettore&);
friend istream& operator>>(istream&,vettore&);
private:
T *v;
int riemp;
int max;
public:
vettore();
vettore(const int);
~vettore(){delete [] v;};
bool full(){return riemp==max;};
bool empty()const;
bool inserisci(const T&);
T& operator[](const int index);
};
#endif
cpp file:
#include "vettore.h"
ostream &operator<<(ostream& out,const vettore & v1){
for(int i=0;i<v1.riemp;i++){
out<<v1.v[i];
}
return out;
}
istream &operator>>(istream& in,vettore &v1){
for(int i=0;i<v1.riemp;i++){
in>>v1.v[i];
}
return in;
}
vettore::vettore(){
riemp=0;
max=10;
v=new T[max];
}
vettore::vettore(const int n):max(n),riemp(0){
v=new T[max];
}
bool vettore::empty()const{
if(riemp==0){
return true;
}else return false;
}
bool vettore::inserisci(const T& n){
if(max==0){
cout<<"Inserisci il massimo di elementi del vettore: ";
cin>>max;
}
if(!full()){
v[riemp]=n;
riemp++;
return true;
}else return false;
}
T& vettore::operator[](const int index){
return v[index];
}
main file:
#include "vettore.h"
int main(int argc, char** argv) {
int riempimento;
vettore vett(1);
regalo r1("Alex",300,"quadrato");
vett.inserisci(r1);
cout<<"Gli elementi del vettore sono: \n";
for(int i=0;i<riempimento;i++){
cout<<vett[i]<<endl;
}
system("PAUSE");
return 0;
}
There are a few issues in your code:
riempimento is not initialised so the for loop in main will perform an unknown number of iterations, likely more than the size of your vector. It would be better to expose the value of riemp from inside the vector and use that in the loop instead.
You need to implement the rule of three, this isn't causing you a problem yet but will in the future if you copy your vettore objects.
If max is 0 when you call inserisci you prompt the user for a value of max, you don't check that cin succeeds and you don't reallocate v to be large enough to contain max elements.
Not a problem but empty could simply be implemented as:
bool vettore::empty()const{
return riemp==0;
}

Overloading i/o operators in C++ for polynomials

I got this project where I have to overload the i/o operators to read and write polynomials. Unfortunately I can't seem to get it to work.
I have the header file:
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <iostream>
using namespace std;
class Polynomial
{
public:
Polynomial();
Polynomial(int degree, double coef[]);
int degree;
double coef[ ];
friend istream& operator>>(istream&,Polynomial& );
friend ostream& operator<<(ostream&,const Polynomial&);
virtual ~Polynomial();
};
#endif // POLYNOMIAL_H
and the cpp file:
#include "Polynomial.h"
#include<iostream>
#include<string>
using namespace std;
Polynomial::Polynomial()
{
//ctor
}
Polynomial::~Polynomial()
{
//dtor
}
Polynomial::Polynomial(int d, double c[])
{
degree = d;
double coef [degree+1];
for(int i = 0; i < d+1; i++)
{
coef[i] = c[i];
}
}
istream& operator>>(istream& x, const Polynomial& p)
{
cout<<"The degree: ";
x>>p.degree;
for(int i = 0; i < p.degree+1; i++)
{
cout<<"The coefficient of X^"<<i<<"=";
x>>p.coef[i];
}
return x;
}
ostream& operator<<(ostream& out, const Polynomial& p)
{
out << p.coef[0];
for (int i = 1; i < p.degree; i++)
{
out << p.coef[i];
out << "*X^";
out << i;
}
return out;
}
In the name I am trying to read a polynomial and then to write another one:
#include <iostream>
using namespace std;
#include "Polynomial.h"
int main()
{
Polynomial p1();
cin >> p1;
int degree = 2;
double coef [3];
coef[0]=1;
coef[1]=2;
coef[3]=3;
Polynomial p(degree, coef);
cout<<p;
return 0;
}
When I run the program it just freezes and I can't seem to find the error.
Any ideas?
Polynomial::Polynomial(int d, double c[])
{
degree = d;
double coef [degree+1];
for(int i = 0; i < d+1; i++)
{
coef[i] = c[i];
}
}
Here, you create local array coef (with non-standard C++ btw) and then assign to it. Your member coeff is not initialized to anything meanigfull (and makes little sense the way it is right now in the first place).
Instead of double coef[] you should use std::vector like this:
struct polynomial {
std::vector<double> coef;
// No need for member varaible degree, vector knows its lengths
polynomial (const std::vector<double> &coeffs) : coef (coeffs) {}
};
And then define all other constructors you need to do something meaningful. Alternatively, you can leave out constructors entirely and directly assign the coefficient vector. Then you can for example functions like
int degree (const polynomial &p) {
return p.coef.size() - 1;
}
or
std::ostream &operator << (std::ostream &out, const polynomial p) {
if (p.coef.size() == 0) {
out << "0\n";
return out;
}
out << p.coeff[0];
for (int i = 1; i < p.coef.size(); ++i)
out << " + " << p.coef[i] << "*X^i";
out << "\n";
return out;
}
(1)
double coef[];
This is non-standard approach to have un-sized/dynamic-sized array on stack. You better give the array some size, OR make it a pointer and allocate memory yourself; OR use vector<double>
(2)
You are creating a local variable in constructor, which will hide the member-variable in class. If you are using pointer approach, you need to allocate it properly here in constructor. With either approach, you should initialize the (member) variable coef with zeros, ideally.
(3)
Polynomial p1();
This effectively declares a function named p1 which would return a Polynomial and not a variable of tyoe Polynomial. You may want to use:
Polynomial p1;

It says "No matching constructor for initialization of 'Fraction'

.cpp
//
// calculator.cpp
//
#include "Fraction.h"
#include<iostream>
#include<stdexcept>
using namespace std;
int main()
{
Fraction x,y; //ERROR IS RIGHT HERE. It says "No matching constructor for initialization of 'Fraction'
char op;
try
{
cin >> x;
cin >> op;
while ( cin && ( op == '+' || op == '-' ) )
{
cin >> y;
if ( op == '+' )
x = x + y;
else
x = x - y;
cin >> op;
}
cout << x << endl;
}
catch ( invalid_argument& e )
{
cout << "Error: " << e.what() << endl;
}
}
.h
#ifndef Fraction_Calculator_Fraction_h
#define Fraction_Calculator_Fraction_h
#include<iostream>
#include<cstdlib>
//Fraction class definition
class Fraction
{
public:
Fraction (int a, int b);
int fraction(int a, int b);
void set(int, int);
int get_numerator(void);
int get_denomenator(void);
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 std::ostream& operator<<(std::ostream &os, const Fraction& n);
friend std::istream& operator>>(std::istream &is, Fraction& n);
Fraction& operator= (const Fraction& n);
int denom;
int numera;
private:
int numerator;
int denomenator;
int denomp;
int nump;
};
#endif
It says "No matching constructor for initialization of 'Fraction' on the first line of the cpp file
I don't understand what it means.
The problem is that your Fraction constructor takes 2 arguments.
Fraction (int a, int b);
and you are invoking it with none
Fraction x,y; //ERROR IS RIGHT HERE. It says "No matching constructor for initialization of 'Fraction'
You should either invoke x and y with the 2 int parameters or define another constructor that takes no arguments.
Provide default constructor like
Fraction()
{
numerator=0;
denomenator0;
denomp0;
nump=0;
}