1
votes

I'm trying to write overloaded insertion and exertion operators but the functions aren't able to access the private members of the class Money.I have "include namespace std;" and "#include " but it won't let me access the private members (dollars and cents).

ostream & operator<<(ostream &osObject, Money &right)
{
    osObject << "Amount of money: $" << right.dollars << ".";
    osObject << right.cents;

    return osObject;
}

istream &operator>>(istream &isObject, Money &right)
{
    isObject >> right.dollars;
    isObject.ignore();
    getline(isObject, right.cents;

    return isObject;
}`

Header file:

#pragma once
class Money{
    // Friends
    friend ostream & operator<<(ostream, Money);
    friend istream & operator>>(istream, Money);
private:
    int dollars;
    int cents;
    void simplify();
//Some other stuff...

I'm getting errors such as: syntax error: missing ';' before '&' 'ostream' : 'friend' not permitted on date declarations missing type specifier- int assumed. C++ does not support default-int

2
The signatures of the function declarations and definitions have to match. - juanchopanza
I also assume getline(isObject, right.cents; is just a typo... - vsoftco

2 Answers

3
votes

Your function definition is

ostream & operator<<(ostream &osObject, Money &right)

Your prototype is

friend ostream & operator<<(ostream, Money);

These are not the same because the first takes an ostream reference argument, and the second uses a plain ostream object. You need to make these match:

friend ostream & operator<<(ostream &, Money &);
0
votes

juanchopanza already gave the answer in his comment. Just in case you want to see it on action:

friend ostream & operator<<(ostream&, Money);
friend istream & operator>>(istream&, Money);

reference signs are missing from the operator arguments ostream and istream.