简体   繁体   中英

Operator Overloading + c++

So I'm supposed to write a program that has num and denom as integer data members of the Fractions class. I'm also supposed to have member functions that can display an object's data values and an overloaded operator function for +. My program says my subscripted items are an invalid data type, but I don't know how to allow for the second fraction without them. Does anyone know how I can fix this? My code is the following:

    #include <iostream>
#include <cmath>

using namespace std;

int a, b, c;

class Fractions
{
    private:
 int num;
 int denom;
 public:
 Fractions(int=1, int=1);
 void operator!(void) const;
 Fractions operator+(const Fractions&) const;
};

Fractions::Fractions(int n, int d)
{
    if( d != 0)
    num= n;
    denom= d;
}

Fractions Fractions::operator+(const Fractions& f) const
{
    a= num/denom;
    b= num[1]/denom[1];
    c= a + b;
    c= (num * denom[1]+ denom * num[1])/(denom * denom[1]);
    return c;
}

int main()
{  
   return 0;
}

You've declared num and denom as int but in your function you're treating them like arrays: b= num[1]/denom[1];

That won't work. What is it you want to do with this line b= num[1]/denom[1]; ? Is the idea to divide by the value of the fraction you're adding? If so maybe what you want is: b = f.num/f.denom;

My algebra isn't the best, but I can't recall using division when adding fractions, but that might be another question (or I might have it wrong).

The most immediate issue that is causing the error you're specifying is caused by trying to do:

b= num[1]/denom[1];

You initialized b, num and denom as an int , not an integer array . But you are trying to access an element of num and denom as if they were arrays.

Either initialize an array of integers for each or dropping the access operator for them will fix the error, but I don't believe it will give you your desired result.

The way you're overloading the '+' operator will not work. Since you have the '+' operator as a member , the object of that class becomes the left hand side of the operator, and what you are passing (const Fractions& f) becomes the right hand side.

You are not using the 'f" variable that you pass in at all, nor are you affecting that instance's members. All you are doing is changing some global variables that really aren't necessary. I recommend you read up on operator overloading since it seems you don't quite understand how it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM