C++Primer Plus对象和类的简单实现()private:public:的合理使用

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何尝不是如此呢

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值