c++ 类与对象练习程序

2016-11-03  本文已影响160人  科学旅行者

代码来源:c++ Primer Plus(第6版)

// stock00.h;
#ifndef STOCKOO_H_
#define STOCK00_H_

#include <string>
using namespace std;

class Stock {//股票;//类;//类对象的默认访问控制;
    private:
        string company;//公司名称;
        long shares;//持有的股票数量;
        double share_val;//每股的价格;
        double total_val;//总价格;
        void set_tot() {total_val = shares * share_val;}//股票的总价格;//类声明常将短小的成员函数作为内联函数;
    public://原型表示;
        void acquire(const 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
// stock00.cpp;
#include <iostream>
#include "stock00.h"
using namespace std;

void Stock::acquire(const string &co, long n, double pr) {//管理对某个公司股票的首次购买;
    company = co;
    if (n < 0) {//股数不能为负;
        cout << "Number of shares can't be negative;" << company << " shares set to 0." << endl;
        shares = 0;
    }
    else {
        shares = n;
    }
    share_val = pr;
    set_tot();//该方法是成员方法;//可以访问私有成员;
}

void Stock::buy(long num, double price) {//增加持有的股票;
    if (num < 0) {
        cout << "Number of shares purchased can't be negative. " << "Transaction is shorted." << endl;
    }
    else {
        shares += num;
        share_val = price;
        set_tot();
    }   
}

void Stock::sell(long num, double price) {//减少持有的股票;
    if (num < 0) {
        cout << "Number of shares purchased can't be negative. " << "Transaction is shorted." << endl;      
    }
    else if (num > shares) {//超过最大值;
        cout << "You can't sell more than you have! " << "Transaction is shorted." << endl;
    }
    else {
        shares -= num;
        share_val = price;
        set_tot();
    }
}

void Stock::update(double price) {//每股价格的变动;
    share_val = price;
    set_tot();
}

void Stock::show() {
    cout << "Company: " << company << " Shares: " << shares << " Share Price: $" << share_val << " Total Worth: $" << total_val << endl;
}
// usestock0.cpp;
#include <iostream>
#include "stock00.h"
int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    Stock s;
    s.acquire("Nanosmart", 20, 12.50);
    s.show();
    s.buy(15, 18.125);
    s.show();
    s.sell(400, 20.00);
    s.show();
    s.buy(300000, 40.125);
    s.show();
    s.sell(300000, 0.125);
    s.show();
    return 0;
}
/*
Company: Nanosmart Shares: 20 Share Price: $12.5 Total Worth: $250
Company: Nanosmart Shares: 35 Share Price: $18.125 Total Worth: $634.375
You can't sell more than you have! Transaction is shorted.
Company: Nanosmart Shares: 35 Share Price: $18.125 Total Worth: $634.375
Company: Nanosmart Shares: 300035 Share Price: $40.125 Total Worth: $1.20389e+00
7
Company: Nanosmart Shares: 35 Share Price: $0.125 Total Worth: $4.375 
*/

主要是练习一下面向对象的基础知识;

上一篇下一篇

猜你喜欢

热点阅读