简体   繁体   中英

Need help Fixing these errors with classes

I need help understanding these error. I have been trying to figure out but can't get to working. Is my algorithm for adding even right?

Here is my current error:

'dem' was not declared in this scope.

I thought the header file takes care of the initialization.

Rational.h

#ifndef _RATIONAL_H_
#define _RATIONAL_H_
#include <iostream>
using namespace std;
class Rational
{


    int num; //p
    int dem; // q


public:

Rational();

Rational(int P, int Q = 1);

void display() const; // _p:_q

void add(const Rational&);

};
#endif

Rational.cpp

#include "Rational.h"
int main()


{

    Rational r1(1 ,2);
    Rational r2(1,4);
    r1.add(r2);
    r1.display();


}
void add(const Rational&h2)
{

    int  i, k;
    Rational fract;
    add(h2);

    i = dem;
    k = h2.dem;
    num*= k;
    dem*=k;
    num = +r2.num*i;
    //return

}

You're defining add() as a global free function, not the member function of class Rational . So you can't access the member variable dem in it.

Change

void add(const Rational&h2)
{
...

to

void Rational::add(const Rational&h2)
{
...

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