我对练习有问题1.20
它说下载此头文件Sales_item.h
/***********************************************************
* filename: sales_item.h
**********************************************************/
#ifndef __SALES_ITEM_H__
#define __SALES_ITEM_H__
#include <iostream>
#include <string>
#include <stdexcept>
//using std::istream; using std::ostream;
class Sales_item
{
/* operations on sales_item object */
public:
double avg_price(void) const;
bool same_isbn(const Sales_item &rhs) const /* inline function */
{
return isbn == rhs.isbn; /* return this->isbn == rhs.isbn*/
}
std::istream &read_item(std::istream &in);
std::ostream &write_item(std::ostream &out) const;
// bool add_item(const sales_item &rhs);
Sales_item add_item(const Sales_item &other);
/* default constructor --- constructor without parameters */
/* default constructor needed to initialize members of built-in type */
Sales_item(): units_sold(0), revenue(0.0) {}
/* private members as before */
private:
std::string isbn; /* ISBN */
unsigned units_sold; /* the number of book sold */
double revenue; /* the total revenue from that book */
};
#if 0
inline
double sales_item::avg_price(void) const
{
if (units_sold)
return (revenue / units_sold); /* return (this->revenue / this->units_sold); */
else
return 0;
}
#endif
inline
double Sales_item::avg_price(void) const
{
using std::runtime_error;
try
{
if (units_sold == 0)
throw runtime_error("when units_sold equal 0, error...");
return (revenue / units_sold); /* return (this->revenue / this->units_sold); */
}
catch (runtime_error err)
{
std::cout << err.what() << std::endl;
return 0;
}
}
#endif /* __SALES_ITEM_H__ */
然后将其与此代码一起使用:
#include <iostream>
#include "Sales_item.h"
int main(int argc, const char * argv[])
{
Sales_item book;
int gne;
// read ISBN, number of copies sold, and sales price
std::cin >> book;
// write ISBN, number of copies sold, total revenue, and average price
std::cout << book << std::endl;
return 0;
}
我在std :: cin和std :: cout行收到错误。这两个错误都是:
二进制表达式的无效操作数('istream'(又名'basic_istream')和'Sales_item')
我正在使用Xcode 5.0。 它可能是什么?
答案 0 :(得分:1)
您的课程不会超载operator <<
和operator >>
,因此您无法将其与cout <<
和cin >>
一起使用。你的班级确实有
std::istream &read_item(std::istream &in);
std::ostream &write_item(std::ostream &out) const;
你可以使用
Sales_item book;
int gne;
// read ISBN, number of copies sold, and sales price
book.read_item(std::cin);
// write ISBN, number of copies sold, total revenue, and average price
book.write_item(std::cout);
答案 1 :(得分:1)
没有运营商&lt;&lt;并且没有运算符&gt;&gt;为您的Sales_item类型定义,因此编译器不知道如何处理语句&#34; cin&gt;&gt;书&#34;和&#34; cout&lt;&lt;本书&#34 ;. 您必须为basic_istream和basic_ostream以及Sales_item编写运算符重载函数。
对于你的情况:
std::ostream& operator<<(std::ostream& os, const Sales_item& item)
{
return item.write_item(os);
}
std::istream& operator>>(std::istream& is, Sales_item& item)
{
return item.read_item(is);
}