首先所创作的包括头文件.h,函数说明.cpp,主函数.cpp必须包含在同一个工程中才能保证各代码之间的通信,按照书上的代码敲上去,即完成了第一个比较完整的关于股票
stock类的创建
代码:
#ifndef STOCK00_H_//头文件声明类
#define STOCK00_H_
#include<string>
using namespace std;
class Stock
{
private:
stringcompany;
longshares;
doubleshare_val;
doubletotal_val;
voidset_tot(){total_val=shares*share_val;}
public:
voidacquire(const string&co,long n,double pr);
voidbuy(long num,double price);
voidsell(long num,double price);
voidupdate(double price);
voidshow();
};
#endif
#include<iostream>//函数的定义声明
#include"stock00.h"
using namespace std;
void Stock::acquire(conststring&co,long n,double pr)
{
company=co;
if(n<0)
{
cout<<"Number of shares can`t be fushu "<<endl;
shares=0;
}
else
shares=n;
share_val=pr;
set_tot();
}
void Stock::buy(long num,double price)
{
if(num<0)
{
cout<<"Warning!!"<<endl;
}
else
{
shares=shares+num;
share_val=price;
set_tot();
}
}
void Stock::sell(long num,double price)
{
if(num<0)
{
cout<<"Waring!!!"<<endl;
}
else
{
shares=shares-num;
share_val=price;
set_tot();
}
}
void Stock::update(double price)
{
share_val=price;
set_tot();
}
void Stock::show()
{
cout<<"Company:"<<company<<endl;
cout<<"Shares:"<<shares<<endl;
cout<<"TotalWorth: "<<total_val<<endl;
}
#include<iostream>//主函数
#include"stock00.h"
int main()
{
Stocknba;
nba.acquire("NanoSmart",20,12.5);
nba.show();
nba.buy(15,18.125);
nba.show();
nba.sell(400,20);
nba.show();
return0;
}
这样就是完成了一个类的创建,在一开始运行总是报错就是因为没有建立在同一个工程中,实在是菜。