前言
终于到了类(QAQ)
10.1 2 3
代码
//头文件:stock00.h
//类声明
#pragma once
#ifndef STOCK00_H_
#define STOCK00_H_
#include <string>
using namespace std;
//Stock类声明,Stock类创建的每一个对象表示一支股票
//将数据和方法组合为一个单元是类的一个重要特性
class Stock
{
//访问控制关键字 public private protected
//公有
public:
//方法原型,类方法可以访问private组件
void acquire(const string & co, long n, double pr);
void buy(long num, double price);
void sell(long num, double price);
void update(double price);
void show();
//私有 面向对象OOP主要的目标之一:隐藏数据,所以数据成员一般在private中定义
//可省略关键字private,class类默认的访问控制类型,struct结构默认的为public
private:
string company;//字符串变量 公司名
long shares;//长整型 股票数
double share_val;//浮点型 每股的价格
double total_val; //股票总价格
//股票总价格 = 股票数 * 每股的价格
void set_tot() {total_val = shares * share_val;}
};
#endif // !STOCK00_H_
//stock00.cpp 定义类成员函数
#include <iostream>
#include "stock00.h"//包含头文件用双引号
//使用作用域解析运算符(::)指出函数所属的类
//acquire函数属于Stock类
void Stock::acquire(const string& co, long n, double pr)
{
company = co;
if (n < 0)
{
cout << "Number of shares can not 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)
{
cout << "Number of shares purchased can not be negative. "
<< "Transaction is aborted.\n";
}
else
{
shares += num;
share_val = price;
set_tot();
}
}
void Stock::sell(long num, double price)
{
if (num<0)
{
cout << "Number of shares sold can not be negative. "
<< "Transaction is aborted.\n";
}
else if (num > shares)
{
cout << "You can not sell more than you have! ";
}
else
{
shares -= num;
share_val = price;
set_tot();
}
}
void Stock::update(double price)
{
share_val = price;
set_tot();
}
void Stock::show()
{
cout << "Company: " << company
<< " Shares: " << shares << '\n'
<< " Share Price: $" << share_val
<< " Total Worth: $" << total_val << endl;
}
//usestock.cpp 使用类,实例化一个类,调用类函数
#include <iostream>
#include "stock00.h"//包含头文件,用双引号
int main()
{
Stock fluffy_the_cat;//创建类实例
fluffy_the_cat.acquire("NanoSmart", 20, 12.50);
fluffy_the_cat.show();
fluffy_the_cat.buy(15, 18.125);
fluffy_th