overloaded friend operator

Im just trying to create an overloaded friend function (am i phrasing that right?) to add two different types of the class 'coins'. I cannot seem to get the syntax right...can someone point me in the right direction?

//the logic implemented in my functions.cpp file

1
2
3
4
5
6
    coins operator+(const coins  &num1, const coins &num2)
    {
    int dollars = num1.dollars + num2.dollars;
    int cents = num1.cents + num2.cents;
    return coins(dollars, cents);
    }

// my functions.h declaration of the friend function
 
    coins operator+(const coins  &num1, const coins &num2);

// my class file declaring a friend in coins.h
 
    friend coins operator+(const coins&, const coins&); 

can anyone point me in the right direction? or should i post the entire code? it keeps telling me
In file included from pa3.cpp:6:0:
pa3functions.h:17:2: error: ‘coins’ does not name a type
In file included from pa3functions.cpp:4:0:
pa3functions.h:17:2: error: ‘coins’ does not name a type
pa3functions.cpp:17:1: error: ‘coins’ does not name a type


Last edited on
figured out i needed the .h files included, but now im wondering if i have to create a separate constructor for the friend function

pa3functions.cpp: In function ‘coins operator+(const coins&, const coins&)’:
pa3functions.cpp:21:32: error: no matching function for call to ‘coins::coins(int&, int&)’
you need to include the name of the class and then two "::" to show the scope you are declaring the function in if you are not defining the function within the class definition. Like
1
2
3
4
5
6
coins::coins operator+(const coins  &num1, const coins &num2)
    {
    int dollars = num1.dollars + num2.dollars;
    int cents = num1.cents + num2.cents;
    return coins(dollars, cents);
    }

also our tutorial for friendship is here ( http://www.cplusplus.com/doc/tutorial/inheritance/ )
you need to include the name of the class and then two "::" to show the scope you are declaring the function in if you are not defining the function within the class definition.


It's not a member of the class, so no. If it was a member of the class, that's still wrong.
So you're saying that if I am defining a function of a class outside of the class definition I don't need to tell the compiler that that function is in the scope of the class ?

Also the compiler is telling you it can't find the a function for the constructor for coins you are using in the return statement there.
Last edited on
Right, I got it all sorted out. cire was right, when i tried using your '::' it failed. Turns out I needed to make another constructor to take the arguments. Thank you for your help though
yeah I see where I derped real hard there about friendship, sorry :p
I had a major miss understanding on how friend functions work xD
Last edited on
Topic archived. No new replies allowed.