类编译
stock.h程序代码:
#ifndef STOCK_h_ #define STOCK_H_ #include<string> //class declaration class Stock { private://not indeed std::string company; long shares; double share_val; double total_val; void set_tot() { total_val = shares*share_val; } public: void acquire(const std::string &co, long n, double pr); void buy(long num, double price); void sell(long num, double price); void update(double price); void show(); }; #endif
stock1.cpp
程序代码:
#include<iostream> #include"stock.h" void Stock::acquire(const std::string &co, long n, double pr) { company = co; if (n < 0) { std::cout << "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(long num, double price) { if (num < 0) { std::cout << "Number of shares can't be negative, " << "Transaction is abort.\n"; } else { shares += num; share_val = price; set_tot(); } } void Stock::sell(long num, double price) { using namespace std; if (num < 0) { cout << "Number of shares can't be negative, " << "Transaction is abort.\n"; } else if (num>shares) { cout << "You can'tsell more than you have! " << "Transaction is abort.\n"; } else { shares -= num; share_val = price; set_tot(); } } void Stock::update(double price) { share_val = price; set_tot(); } void Stock::show() { std::cout << "Company: " << company << " Shares: " << shares << '\n' << " Shares Price:$ " << share_val << " Total Worth:$ " << total_val << '\n'; }
stock2.cpp
程序代码:
#include "stdafx.h" #include<iostream> #include"stock.h" int _tmain(int argc, _TCHAR* argv[]) { Stock vital; vital.acquire("NanoSmart", 20, 12.50); vital.show(); vital.buy(15, 18.125); vital.show(); vital.sell(400, 20.00); vital.show(); vital.buy(300000, 40.125); vital.show(); vital.sell(300000, 0.125); vital.show(); return 0; }
The err