stock00.h文件实现了,类和私有变量,私有函数(类的内部使用,外部不可见),共有函数的申明(void acquire(),void buy(),void sell,void update(),void show()).
下面通过某上市公司股票(Stock类)的买卖做案列,分析下面程序
1,Private:申明私有变量和函数的申明
2.public:申明公有函数和变量(本案例没有公用变量)
#pragma once
//stock00.h -- stock class interface
//version 00
#ifndef STOCK00_H_
#define STOCK00_H_
#include<string>
class Stock //class 类的申明
{
private://私有成员和函数的申明
std::string company; //公司名称
long shares;//所持股票的数量
double share_val;//每股价格
double total_val;//股票总值
void set_tot()//内联函数,和inline同理,定义位于类申明中的函数自动成为内联韩式
{
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 // !STOCK00_H_
几个公有函数的实现
//stock00.cpp--implementing the stock class
//version 00
#include<iostream>
#include"stock00.h"
void Stock::acquire(const std::string& co, long n, double pr)
{
company = co;
if (n<0)
{
std::cout << "输入股票的数量不正确" << company << "被设置为0";
shares = 0;
}
else
{
shares = n;
}
share_val = pr;
set_tot();
}
void Stock::buy(long num, double price)
{
if (num<0)
{
std::cout << "股票的数量不能是负数" << "请求终止";
}
else
{
shares += num;
share_val = price;
set_tot();
}
}
void Stock::sell(long num, double price)
{
using std::cout;
if (num<0)
{
cout << "股票的数量不能是负数" << "请求终止";
}
else if (num>shares)
{
cout << "你输入的数量超过你持有的数量" << "请求终止"<<"\n";
}
else
{
shares -= num;
share_val = price;
set_tot();
}
}
void Stock::update(double price)
{
share_val = price;
set_tot();
}
void Stock::show()
{
using std::cout;
using std::ios_base;
//设置输入格式 #.###
ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
std::streamsize prec = cout.precision(3);
cout << "公司 " << company
<< "股票:" << shares << "\n"
<< "股价:$" << share_val;
//设置输出格式 #.##
cout.precision(2);
cout<< "总价值:$" << total_val << "\n";
//回复原始格式
cout.setf(orig, ios_base::floatfield);
cout.precision(prec);
}
主函数的实现
#pragma region 练习1.10.3
//usestck0.cpp -- the client program
//compile with stock00.cpp
#if 1
#include <iostream>
#include"stock00.h"
int main()
{
Stock fluffyTheCat;
fluffyTheCat.acquire("NamoSmart", 20, 12.50);
fluffyTheCat.show();
fluffyTheCat.buy(15, 18.125);
fluffyTheCat.show();
fluffyTheCat.sell(400, 20.00);
fluffyTheCat.show();
fluffyTheCat.buy(300000, 40.125);
fluffyTheCat.show();
fluffyTheCat.sell(300000, 0.125);
fluffyTheCat.show();
return 0;
}
#endif
#pragma endregion
本案例就是类设计的方法。
案例虽然简单,但是这代表了一种设计思想,就是面向对象的一种思想,其实C也有这种思想,更多的人会认为C++是面向对象,其实C何尝不是如此呢

被折叠的 条评论
为什么被折叠?



