(2011.07.14) 类的基本应用实例。
2011-07-14 22:08
281 查看
2011.07.14 类的基本应用实例。
// stocks.cpp -- the whole program #include <iostream> #include <cstring> class Stock // class declaration { private: char company[30]; int shares; double share_val; double total_val; void set_tot(){ total_val = shares * share_val;} public: void acquire(const char* co, int n, double pr); void buy(int num, double price); void sell(int num, double price); void update(double price); void show(); }; // note semicolon at the end void Stock::acquire(const char* co, int n, double pr) { std::strncpy(company, co, 29); // truncate co to fit company company[29] = '\0'; if (n < 0) { std::cerr << "Number of shares can't be negative." << company << " shares set to 0. \n"; shares = 0; } else shares = n; share_val = pr; set_tot(); } void Stock::buy(int num, double price) { if(num < 0) { std::cerr << "Number of shares purchased can't be negative." << "Transaction is aborted.\n"; } else { shares += num; share_val = price; set_tot(); } } void Stock::sell(int num, double price) { using std::cerr; if (num < 0) { cerr << "Number of shares sold can't be negative. " << "Transaction is aborted.\n"; } else if (num > shares) { cerr << "You can't sell more than you have!" << " Transaction is aborted. \n"; } else { shares -= num; share_val - price; set_tot(); } } void Stock::update(double price) { share_val = price; set_tot(); } void Stock::show() { using std::cout; using std::endl; cout << "Company: " << company << " Shares: " << shares << endl << " Share Price: {1}quot; << share_val << " Total Worth: {1}quot; << total_val << endl; } int main() { using std::cout; using std::ios_base; Stock stock1; stock1.acquire("NanoSmart", 20, 12.50); cout.setf(ios_base::fixed); cout.precision(2); cout.setf(ios_base::showpoint); stock1.show(); stock1.buy(15, 18.25); stock1.show(); stock1.sell(400, 20.00); stock1.show(); return 0; }
相关文章推荐
- 图文详解!DevExpress XtraScheduler日程管理控件应用实例(1)-- 基本使用
- 实例解析iOS中音乐播放器应用开发的基本要点
- Java Web 应用实例 servlet实现oracle 基本增删改查
- 从基本应用实例快速步入XML编程世界
- VC++ Datagrid应用实例详解系列(1) - 基本功能
- Libevent基本应用实例--专为懒人定制
- 数据结构 学习笔记(一):基本概念:什么是数据结构和算法,应用实例
- Java并发32:CyclicBarrier的基本方法和应用场景实例
- ARM—Linux基本数据类型综合应用实例
- android 蓝牙锁应用开发实例(二)客户端基本页面
- Java并发33:Semaphore基本方法与应用场景实例
- 一些vc的基本知识,创建应用实例的步骤
- 一些vc的基本知识,创建应用实例的步骤
- 关于接口的基本应用实例讲解
- JavaWeb应用实例:用servlet实现oracle 基本增删改查
- 一些vc的基本知识,创建应用实例的步骤
- Unity3D中平衡类游戏player的基本应用实例
- Spring---AOP基本概念以及Advice5种类型的通知注解应用实例
- xml基本操作和保存配置文件应用实例
- 图算法(三):两种基本图算法的应用实例