10.1 过程性编程和面向对象编程
10.2 抽象和类
10.3 类的构造函数和析构函数
类的定义和使用(买卖股票)
头文件stock10.h
#ifndef __STOCK00__H__
#define __STOCK00__H__
#include <string>
class Stock {
// pravate的内容只能通过public访问
private:
std::string company; // 公司名字
long shares; // 股票的数量
double share_val; // 每只股票的价格
double total_val; // 股票总价值
void set_total() {
total_val = shares * share_val;
}; // 函数在类的声明中定义,将自动成为内联函数
public:
// 默认构造函数
Stock();
// 构造函数
Stock(const std::string &co, long n = 0, double pr = 0.0);
// 析构函数
~Stock();
// 买入股票:买入数量,买入价格
void buy(long num, double price);
// 卖出股票:卖出数量,卖出价格
void sell(long num, double price);
// 传递最新价格
void update(double price);
// 显示股票信息
void show() const;
};
#endif // ! __STOCK00_H__
源代码usestock2.cpp
#include <iostream>
#include "stock10.h"
int main() {
using std::cout;
cout << "Using constructors to create new objects\n";
Stock stock1("NanoSmart", 12, 20.0); // 隐式调用
stock1.show();
Stock stock2 = Stock("Boffo Objects", 2, 2.0); // 显式调用
stock2.show();
cout << "Assigning stock1 to stock2:\n";
stock2 = stock1; // 类的对象可以相互之间对拷
cout << "Listing stock1 and stock2:\n";
stock1.show();
stock2.show();
cout << "Using a constuctor to reset an Object\n";
stock1 = Stock("Nifty Foods", 10, 50.0); // 创建临时变量再赋值
cout << "Revised stock1:\n";
stock1.show();
cout << "Done\n";
const Stock land = Stock{ "Klu Pro" };
// show()函数要接收const的对象,函数定义时要在函数名后面加上const
land.show();
return 0;
}
源代码stock10.cpp
#include <iostream>
#include "stock10.h"
Stock::Stock() {
std::cout << "Default constructor called\n";
company = "no name";
shares = 0;
share_val = 0.0;
total_val = 0.0;
}
Stock::Stock(const std::string &co, long n, double pr) {
company = co;
if (n < 0) {
std::cout << "Number can't be negative, shares set to 0" << std::endl;
shares = 0;
}
else shares = n;
share_val = pr;
set_total();
}
Stock::~Stock() {
std::cout << "Bye, " << company << "!\n";
}
void Stock::buy(long num, double price) {
if (num < 0) {
std::cout << "Number can't be negative, transatcion failed." << std::endl;
}
else {
shares += num;
share_val = price;
set_total();
}
}
void Stock::sell(long num, double price){
if (num < 0) {
std::cout << "Number can't be negative, transatcion failed." << std::endl;
}
else if (num > shares){
std::cout << "Number is more than you have, transaction failed." << std::endl;
}
else {
shares -= num;
share_val = price;
set_total();
}
}
void Stock::update(double price) {
share_val = price;
set_total();
}
void Stock::show() const{ // 代表函数不会修改值,可以接收const的对象
std::cout << "Company: " << company << std::endl;
std::cout << "Shares: " << shares << std::endl;
std::cout << "Share price: " << share_val << std::endl;
std::cout << "Total worth: " << total_val << std::endl;
}
10.4 This指针
This指针的使用(比较股票总值)
// 比较股票的总金额,并返回一个对象
// 第2个const:函数不会修改被显式访问的对象
// 第3个const:函数不会修改被隐式访问的对象
// 第1个const:函数会返回一个const Stock对象
const Stock & Stock::topval(const Stock & s) const{
if (s.total_val > total_val) // total_val == this->total_val
return s;
else
return *this; // this是一个指针,要返回值需要取值运算符
}
10.5 对象数组
使用对象数组(找出总价值最大的股票)
int main(){
Stock stocks[4] = {
Stock("NanoSmart", 12, 20.0),
Stock("Boffo Objects", 200, 2.0),
Stock("Monolithic Obelisks", 130, 3.25),
Stock("Fleep Enterprises", 60, 6.5)
};
std::cout << "Stock holdings:\n";
int st;
for (st = 0; st < 4; st++)
stocks[st].show();
const Stock * top = &stocks[0];
for (st = 1; st < 4; st++)
// 使用指针的方法返回一个对象,然后再取地址赋给top
top = &top->topval(stocks[st]);
std::cout << "\nMost valuable holding:\n";
top->show();
return 0;
}
10.6 类作用域
10.7 抽象数据类型
使用类实现抽象数据类型(栈)
头文件stack.h
#ifndef __STACK__H__
#define __STACK__H__
typedef unsigned long Item; // 类型别名,如果需要放别的类型就改这里
class Stack {
private:
enum {MAX = 10}; // 创建枚举类型,遇到MAX就替换成10
Item items[MAX];
int top; // 栈顶的指针
public:
Stack();
bool isempty() const; // 栈是否为空
bool isfull() const; // 栈是否满了
bool push(Item &item); // 入栈,成功返回1,失败返回0
bool pop(Item &item); // 出栈,成功返回1,失败返回0
};
#endif
源文件stacker.cpp
#include <iostream>
#include "stack.h"
using namespace std;
int main() {
char ch;
unsigned long po;
Stack st;
cout << "Enter 'A' to push to stack\n";
cout << "Enter 'P' to pop from stack\n";
cout << "Enter 'Q' to quit\n";
while (cin >> ch && ch != 'Q') {
while (cin.get() != '\n') // 删除输入行中剩余部分
continue;
switch (ch) {
case 'A':
cout << "Enter a number:" << endl;
cin >> po;
if (st.isfull())
cout << "Stack already full." << endl;
else
st.push(po);
break;
case 'P':
if (st.isempty())
cout << "Stack is empty." << endl;
else {
st.pop(po);
cout << po << " is poped." << endl;
}
break;
}
cout << "Enter 'A' to push to stack\n";
cout << "Enter 'P' to pop from stack\n";
cout << "Enter 'Q' to quit\n";
}
return 0;
}
源文件stack.cpp
#include "stack.h"
Stack::Stack() {
top = 0;
}
bool Stack::isempty() const {
return top == 0;
}
bool Stack::isfull() const {
return top == MAX;
}
bool Stack::push(Item &item){
if (top < MAX) {
items[top++] = item; // 先操作,后加加
return true;
}
else
return false;
}
bool Stack::pop(Item &item) {
if (top > 0) {
item = items[--top]; // 先减减,再操作
return true;
}
else
return false;
}