c++小程序

xiaoxiao2021-02-28  55

// stock00.h // Created by 吕百杨 on 2016/10/8. // #ifndef STOCK00_H_STOCK00_H #define STOCK00_H_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;}//是内联函数,短小的函数就行;另一种形式在下面 //可以立即定义或者如其他函数一样用原型表示,对于描述函数的借口来说足够 //stock类对set_tot函数做的就是一种封装,将实现细节放在一起,并将它们与抽象分开 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(); //sell 和 update 都是 "方法" //void Stock::update(double price),::表示了函数所属的类(说明可以将另一个类的成员名字也定义成update) //此Stock类的其他函数不比使用::即可使用update()方法 };//此处有冒号 /* * inline void Stock::set_tot() //要使用inline在最前面,其他的与定义一个函数差不多,再注意Stock::std * { * total_val=shares*share_val; * } * * * * */ /* * Stock::Stock(const std::string &co,long n,double pr) 此为构造函数,注意stock::stock, * 与acquire函数相同,区别在于程序声明对象时,自动调用构造函数 { 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(); } */ #endif //STOCK00_H_STOCK00_H//stock00.cpp #include <iostream>#include "stock00.h"//Stock kate,joe; 这创建了两个类对象,一个为kate,一个为joe 创建时每个对象都有自己的存储空间,用于储存其内部的变量和类成员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 is 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! " << "transacton 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<<"companny "<<company <<"shares "<<shares<<'\n' <<"share price: "<<share_val <<"total price: "<<total_val<<'\n';}
转载请注明原文地址: https://www.6miu.com/read-96705.html

最新回复(0)