面向对象编程(OOP)特性:抽象、封装、多态、继承;
抽象:将一个对象的属性抽象出来形成一个类别;
封装:将实现细节放在一起并将它们与抽象分开称为封装;
多态:函数重载,多种参数传递形式;
继承:类的继承,子类父类;
程序设计:
1、首先考虑对象,描述对象所需的数据以及描述用户与数据交互所需的操作。
2、完成对接口的描述后,需要确定如何实现接口和数据存储
3、使用新的设计方案创建出程序
类
类声明一般包含私有数据成员,公共函数成员。有时候也会包含私有函数成员,其可以通过共共函数成员调用。
类文件一般只提供接口,可以理解为接口文件。一般在另一个文件中补充类中的函数
如类的声明文件:
//stock.h -- stock class interface接口 接口文件,提供接口
//version 00
#ifndef STOCK00_H_ //保护它不让多重引用 就是保护的意思
#define STOCK00_H_
#include <string>
class Stock //class declaration
{
private :
std::string company;
long shares; //一般数据都是私有的,函数是公共的
double share_val;
double total_val;
void set_tot(){ 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.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 << "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"
<< "Transaction 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 << "Company: " << company
<< " Shares: " << shares << std::endl
<< " Share price: $ " << share_val
<< "Total Worth: $" << total_val << std::endl;
}
然后可以就在函数中新建对象了