您的位置:首页 > 编程语言 > C语言/C++

C++ Primer Plus学习:第十章 对象和类(1)

2011-09-09 11:36 134 查看
类型

决定数据对象需要的内存数量

决定如何解释内存中的位(long和float在内存中占用的位数相同,但将它们转换为数值的方法不同)

决定可使用数据对象执行的操作或方法



将数据表示和操作数据的方法组合成一个整洁的包

定义

类声明:以数据成员的方式描述数据部分,以成员函数的方式描述公有接口

类方法定义:描述如何实现类成员函数

类声明提供了类的蓝图,而方法定义则提供了细节

eg

#include <iostream>
#include <cstring>

class Stock
{
private:
char company[30];
int shares;
double share_val;
double total_val;
void set_tot(){total_val = shares*share_val;};
public:
void acquire(const char *co,int n,double pr);
void buy(int num,double );
void sell(int num,double price);
void update(double price);
void show();
};

void Stock::acquire(const char *co,int n,double pr)
{
std::strncpy(company,co,29);
company[29] = '\0';
if(n<0)
{
std::cerr<<"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(int num,double price)
{
if(num<0)
{
std::cerr<<"Number of shares purchased can't be nagative."<<"Transaction is aborted.\n";
}
else
{
shares = num;
share_val = price;
set_tot();
}
}

void Stock::sell(int num,double price)
{
using std::cerr;
if(num<0)
{
cerr<<"Number of share sold can't be negative."<<"Transaction is aborted.\n";
}
else if(num>shares)
{
cerr<<"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()
{
using std::cout;
using std::endl;

cout<<"Company: "<<company<<", Share: "<<shares<<endl;
cout<<"Shares Price:{1}quot;<<share_val<<", Total Worth:{1}quot;<<total_val<<endl;
}

int main()
{
using std::cout;
using std::ios_base;
Stock stock1;
stock1.acquire("NanoSmart",20,12.50);
//--------设置输出格式begin--------
cout.setf(ios_base::fixed);
cout.precision(2);
cout.setf(ios_base::showpoint);
//--------设置输出格式end----------
stock1.show();
stock1.buy(15,18.25);
stock1.show();
stock1.sell(400,20.00);
stock1.show();

system("pause");
return 0;
}


接口

供两个系统交互时使用

Note

对于类,我们说公共接口。公众(public)是使用类的程序,交互系统由类对象组成,而接口由编写类的人提供的方法组成。

接口让程序员能够编写与类对象交互的代码,从而让程序能够使用类对象

不必在类声明中使用关键字private,因为这是类对象的默认访问控制
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: