教学文库网 - 权威文档分享云平台
您的当前位置:首页 > 精品文档 > 学前教育 >

C++ Primer第一章 快速入门课后习题代码(3)

来源:网络收集 时间:2026-08-23
导读: Sales_item); // other members as before public: // operations on Sales_item objects double avg_price() const; bool same_isbn(const Sales_item } // default constructor needed to initialize members of

Sales_item& operator+=(const Sales_item&); // other members as before public:

// operations on Sales_item objects double avg_price() const;

bool same_isbn(const Sales_item &rhs) const { return isbn == rhs.isbn; }

// 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;

unsigned units_sold; double revenue; };

// nonmember binary operator: must declare a parameter for each operand

Sales_item operator+(const Sales_item&, const Sales_item&);

inline bool

operator==(const Sales_item &lhs, const Sales_item &rhs) {

// must be made a friend of Sales_item return lhs.units_sold == rhs.units_sold && lhs.revenue == rhs.revenue && lhs.same_isbn(rhs); }

inline bool

operator!=(const Sales_item &lhs, const Sales_item &rhs)

{

return !(lhs == rhs); // != defined in terms of operator== }

using std::istream; using std::ostream;

// assumes that both objects refer to the same isbn inline

Sales_item& Sales_item::operator+=(const Sales_item& rhs) {

units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; }

// assumes that both objects refer to the same isbn inline

Sales_item

operator+(const Sales_item& lhs, const Sales_item& rhs) {

Sales_item ret(lhs); // copy lhs into a local object that we'll return

ret += rhs; // add in the contents of rhs return ret; // return ret by value }

inline istream&

operator>>(istream& in, Sales_item& s) {

double price;

in >> s.isbn >> s.units_sold >> price; // check that the inputs succeeded if (in)

s.revenue = s.units_sold * price;

else

s = Sales_item(); // input failed: reset object to default state

return in; }

inline

ostream&

operator<<(ostream& out, const Sales_item& s) {

out << s.isbn << \ << s.revenue << \ s.avg_price(); return out; }

inline

double Sales_item::avg_price() const {

if (units_sold)

return revenue/units_sold; else

return 0; }

#endif

C++ Primer第一章 快速入门课后习题代码(3).doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.jiaowen.net/wendang/592031.html(转载请注明文章来源)
Copyright © 2020-2025 教文网 版权所有
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:78024566 邮箱:78024566@qq.com
苏ICP备19068818号-2
Top
× 游客快捷下载通道(下载后可以自由复制和排版)
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
注:下载文档有可能出现无法下载或内容有问题,请联系客服协助您处理。
× 常见问题(客服时间:周一到周五 9:30-18:00)