简体   繁体   中英

Error while Overloading the '>>' operator

I'm designing a Money object for a project. I'm not asking for help on implementation, because I really have to figure that out myself, but I'm getting the following error (and this is the only error!)

error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)

I don't have errors in my Money.h or Money.cpp file, just the test.cpp file. Here are the contents of all three files:

Money.h

#ifndef MONEY_H
#define MONEY_H
#include <iostream>
#include <string>
class Money
{
public:
    Money( );
    Money( int dollars, int cents );

    friend std::istream& operator>>( std::istream &i, Money &m );

private:
    int dollars;
    int cents;
};
#endif

Money.cpp

#include "Money.h"

Money::Money(void) : dollars(0), cents(0)
{

}

Money::Money( int dollars, int cents ) : dollars(dollars), cents(cents)
{

}

std::istream& operator>>( std::istream &i, Money &m )
{

    int d;
    int c;
    char input;
    std::string dollars = "";
    std::string cents = "";

    input = std::cin.peek();
    while (std::cin.peek() != '.')
    {
        if ( !( (input >= '0') && (input <= '9') ) )
        {
            std::cin.ignore();
        }
        else
        {
            input = std::cin.get();
        }

        dollars += input;
    }

    if ( std::cin.peek() == '.')
    {
        std::cin.ignore();
    }

    std::cin >> cents;

    d = atoi(dollars.c_str());
    c = atoi(cents.c_str());

    m = Money(d, c);

    return i;
}

Finally, test.cpp:

#include "Money.h"

int main()
{
    Money newMoney();
    std::cout << "Enter a money object!" << std::endl;
    std::cin >> newMoney;
}

So, there you have it. I'm pretty sure that's about as trimmed-down as I can get it.

You don't have enough data in the question. But, consulting my crystal ball, I see that you have defined operator>> in your .CPP file, but failed to declare operator>> in your .H.

Add the following line to your .H:

std::istream& operator>>( std::istream &i, Money &m );

My crystal ball is faulty. The error lies here:

Money newMoney();

That doesn't declare a Money object named newMoney . That declares an external function named newMoney that takes no paramaters and returns a Money object. Replace that line with this:

Money newMoney;

Nothing pops out other than normally I would define this

std::istream& operator>>

as

friend std::istream& operator>>

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