stock10.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // stock1.cpp – Stock class implementation with constructors, destructor added
  2. #include <iostream>
  3. #include "stock10.h"
  4. // constructors (verbose versions)
  5. Stock::Stock() // default constructor
  6. {
  7. std::cout << "Default constructor called\n";
  8. company = "no name";
  9. shares = 0;
  10. share_val = 0.0;
  11. total_val = 0.0;
  12. }
  13. Stock::Stock(const std::string & co, long n, double pr)
  14. {
  15. std::cout << "Constructor using " << co << " called\n";
  16. company = co;
  17. if (n < 0)
  18. {
  19. std::cout << "Number of shares can't be negative; "
  20. << company << " shares set to 0.\n";
  21. shares = 0;
  22. }
  23. else
  24. shares = n;
  25. share_val = pr;
  26. set_tot();
  27. }
  28. // class destructor
  29. Stock::~Stock() // verbose class destructor
  30. {
  31. std::cout << "Bye, " << company << "!\n";
  32. }
  33. // other methods
  34. void Stock::buy(long num, double price)
  35. {
  36. if (num < 0)
  37. {
  38. std::cout << "Number of shares purchased can't be negative. "
  39. << "Transaction is aborted.\n";
  40. }
  41. else
  42. {
  43. shares += num;
  44. share_val = price;
  45. set_tot();
  46. }
  47. }
  48. void Stock::sell(long num, double price)
  49. {
  50. using std::cout;
  51. if (num < 0)
  52. {
  53. cout << "Number of shares sold can't be negative. "
  54. << "Transaction is aborted.\n";
  55. }
  56. else if (num > shares)
  57. {
  58. cout << "You can't sell more than you have! "
  59. << "Transaction is aborted.\n";
  60. }
  61. else
  62. {
  63. shares -= num;
  64. share_val = price;
  65. set_tot();
  66. }
  67. }
  68. void Stock::update(double price)
  69. {
  70. share_val = price;
  71. set_tot();
  72. }
  73. void Stock::show()
  74. {
  75. using std::cout;
  76. using std::ios_base;
  77. // set format to #.###
  78. ios_base::fmtflags orig =
  79. cout.setf(ios_base::fixed, ios_base::floatfield);
  80. std::streamsize prec = cout.precision(3);
  81. cout << "Company: " << company
  82. << " Shares: " << shares << '\n';
  83. cout << " Share Price: $" << share_val;
  84. // set format to #.##
  85. cout.precision(2);
  86. cout << " Total Worth: $" << total_val << '\n';
  87. // restore original format
  88. cout.setf(orig, ios_base::floatfield);
  89. cout.precision(prec);
  90. }