c++小程序

//     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.cnblogs.com/LvBaiYang/p/5942445.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值