Heim > Fragen und Antworten > Hauptteil
//在C++ Primer中文版230页Sales_data类中,有个问题不太明白。当接口函数只有 combine的时候,编译成功,一旦加入 read 和 print两个非成员接口函数,则编译报错,请指教
struct Sales_data{
std::string isbn()const {return bookNo;}
Sales_data& combine(const Sales_data &rhs);
std::string bookNo;
unsigned uints_sold =0;
double revenue = 0.0;
};
Sales_data& Sales_data::combine(const Sales_data &rhs)
{
uints_sold += rhs.uints_sold;
revenue += rhs.revenue;
return *this;
}
std::istream &read (istream &is , Sales_data &item)
{
double price = 0;
is >> item.bookNo >> item.uints_sold >> price;
item.revenue = price * item.uints_sold ;
return is;
}
std::ostream &print(ostream &os, const Sales_data &item)
{
os << item.isbn() << " " << item.uints_sold << " " << item.revenue << " ";
return os;
}
ringa_lee2017-04-17 14:01:56
请在 #include <string>
后面加上一句using namespace std;
贴代码的时候不要直接贴,使用添加代码的功能。
#ifndef SALES_DATA_H_INCLUDED
#define SALES_DATA_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
struct Sales_data {
std::string isbn() const
{
return(bookNo);
}
Sales_data & combine( const Sales_data &rhs );
std::string bookNo;
unsigned uints_sold = 0;
double revenue = 0.0;
};
Sales_data & Sales_data::combine( const Sales_data &rhs )
{
uints_sold += rhs.uints_sold;
revenue += rhs.revenue;
return(*this);
}
std::istream &read(istream &is, Sales_data &item )
{
double price = 0;
is >> item.bookNo >> item.uints_sold >> price;
item.revenue = price * item.uints_sold;
return(is);
}
std::ostream &print( ostream &os, const Sales_data &item )
{
os << item.isbn() << " " << item.uints_sold << " " << item.revenue << " ";
return(os);
}
#endif /* SALES_DATA_H_INCLUDED */