【发布时间】:2012-03-25 10:56:41
【问题描述】:
我正在为一个项目设计一个 Money 对象。我不是在寻求实施方面的帮助,因为我真的必须自己弄清楚,但我收到以下错误(这是唯一的错误!)
错误 C2678: 二进制 '>>' : 未找到采用 'std::istream' 类型的左侧操作数的运算符(或没有可接受的转换)
我的 Money.h 或 Money.cpp 文件中没有错误,只有 test.cpp 文件。以下是所有三个文件的内容:
钱.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;
}
最后是test.cpp:
#include "Money.h"
int main()
{
Money newMoney();
std::cout << "Enter a money object!" << std::endl;
std::cin >> newMoney;
}
所以,你有它。我很确定这是我能做到的。
【问题讨论】:
-
与其在 google 上闲逛,不如试试这个:将您的程序缩减为仍然显示错误的最小程序。要么你会在这个过程中发现错误,要么你有一个有用的测试用例要发布到 StackOverflow。 sscce.org
-
你声明
std::istream& operator>>(std::istream& is, Money& m)你的测试代码可以看到吗? -
我的 Money.h 文件中现在有
friend std::istream& operator>>( std::istream &i, Money &m );,函数在实现文件中定义。我仍然有同样的错误。
标签: c++ visual-c++ operator-overloading istream