1

I've been working on a practice program (C++) involving operator overloading and friend functions - one of these friend functions (ostream& operator<<(ostream &out, const rational &robj)) accesses (or is supposed to access) a private member function GCD() within a class 'rational'. Defining the GCD() function turned out alright, but it is the aforementioned friend function that is giving me a problem, as when I refer to GCD() my IDE labels it as an error, saying the private function is unidentified. I would assume that it is a matter of placement of the function headers and such, but this has left me absolutely boggled. Below is the link to my code:

http://pastebin.com/NetfQHY1

Any help is extremely welcome! Thank you all so much! :)

Charybdis
  • 83
  • 8
  • 2
    Do not share links to your code! Try pasting the minimal code here. – CinCout Apr 02 '15 at 04:16
  • `operator<<` is not a member function — you need to call `GCD` on a suitable object. But you probably want to simplify after each operation, not on output. – molbdnilo Apr 02 '15 at 06:04

2 Answers2

1

It sounds like you need a forward declaration. Make sure there is a declaration of the private function before the code that needs to call it. So you would have this forward declaration in addition to the actual definition of the function.

You may need to use a header file for this – depending on whether the caller is in a different source file. If so, you would place the forward declaration in the header file and then include that header file in all of the other files that use the function.

For further reading, check out this other stackoverflow post: C++ Forward Declaration.

Community
  • 1
  • 1
Sildoreth
  • 1,883
  • 1
  • 25
  • 38
  • There are foward declarations (prototypes?) for both functions, though. But I will play around with the positioning – Charybdis Apr 02 '15 at 12:02
1

In the code you provided, it looks like your problem is that you are trying to call GCD as a stand-alone function. However, you defined it as a method – a function that is meant to be invoked on an object.

So in order to invoke GCD, you would have to do it like this:

rationalInstance.GCD();

Since your implementation of operator<< was as a stand-alone function, you cannot do this:

GCD();

...which is the same as:

this->GCD();

There is no concept of this in the context of a stand-alone function.

Given your definition of operator<<, I think this is maybe what you want:

ostream& operator<<(ostream &out, const rational &robj)
{
    int divisor = robj.GCD();
}

For this to compile, though, you may have to update the definition/declaration of GCD to indicate that it doesn't modify the object:

int rational::GCD() const;

...because your rational parameter is marked as const.

Sildoreth
  • 1,883
  • 1
  • 25
  • 38