下面是头文件stock00.h的内容:
#ifndef STOCK00_H_#define STOCK00_H_#include<string>class Stock{PRivate://私有,不可以被外界直接访问,只能通过公有函数访问 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();};#endifprivate是类对象默认访问控制。接下来的file1是函数的定义:
#include<iostream>//此文件是对头文件中的函数定义#include"stock00.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 purchased can't be negative." << "Transaction if aborted./n"; } else { shares += num; share_val = price; set_tot(); }}void Stock::sell(long num, double price){ using std::cout; if (num < 0) { cout << "Number of shares sold can't be negative." << "Transaction is aborted./n"; } else if(num>shares) { cout << "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(){ std::cout << "Company:" << company << " Shares: " << shares << '/n' << "Share price :$" << share_val << " Total Worth: $" << total_val << std::endl;}
新闻热点
疑难解答