2012-7-19
今日上网查了类的三大特性:继承、多态、封装。
封装的概念好比一台电脑,你学电脑的时候只需学会诸如开机,关机,装软件等即可,无需去了解它的内部是如何发动。只要这些东西封装起来我们能够用就行了。
继承,继承起到了对类在次分类的作用,比如,有个类再次分类的作用,比如,有个类“动物”,“哺乳动物”继承“动物”,再往下“马”又继承了“哺乳动物”这个类。在这里,我们从下往上讲,首先,我们把某种东西划分出来,叫做“马”(还有“牛”、“鱼”等),接着,我们发现,“马”,“羊”等还有很多共同的特点,于是,我们再次分类,我们则有了“动物”。但实际开发中,我们一般是从上往下定义的,即先有了“动物”,再有“哺乳动物”,最后有“马”。
多态允许你将父对象设置成为和一个或更多个的他的子对象相等的技术,赋值之后,父对象就可以根据当前赋值给它的子对象的特性以不同的方式运作。简单的说:允许将子类类型的指针赋给父类类型的指针。
对以上的理解:因为父类中有的,子类中都有,但是子类中有的,父类中不一定有。所以,父亲指针指向子类,使用的操作肯定正确但是子类指针指向父类,访问的方法可能父类中没有,会出错。
关键字private 标识只能通过公共成员函数访问的类成员(数据隐藏)。
关键字public 标识组成类的公共接口的类成员(抽象)。
编写了一个类的程序:
stack.h
#ifndefSTACK_H_
#defineSTACK_H_
typedef unsigned long Item;
classStack
{
private:
enum {MAX =10}; //constantspecific to class
Item items[MAX]; //holds stackitems
inttop; //indexfor top stack item
public:
Stack();
boolisempty()const;
boolisfull()const;
//push()returnsfalse if stack already is full true otherwise
bool push(const Item & item); //add item tostack
//pop()returnsfalse if stack already is empty,true otherwise
boolpop(Item & item); //pop top into item
};
#endif
stack.cpp
#include "stack.h"
Stack::Stack() //create an emptystack
{
top = 0;
}
boolStack::isempty()const
{
return top== 0;
}
boolStack::isfull()const
{
return top== MAX;
}
boolStack::push(const Item & item)
{
if(top <MAX)
{
items[top++] = item;
return true;
}
else
return false;
}
boolStack::pop(Item & item)
{
if(top >0)
{
item = items[--top];
return true;
}
else
return false;
}
stacker.cpp
#include<iostream>
#include<cctype>
#include"stack.h"
intmain()
{
using namespace std;
Stack st; //create an empty stack
char ch;
unsigned long po;
cout << "Pleaseenter A to add a purchase order, \n"
<<"P to process a PO,or Q to quit.\n";
while(cin>> ch && toupper(ch) != 'Q')
{
while(cin.get()!='\n')
continue;
if(!isalpha(ch))
{
cout << '\a';
continue;
}
switch(ch)
{
case 'A':
case 'a': cout << "Entera PO number to add: ";
cin>> po;
if(st.isfull())
cout << "stackalready empty\n";
else
st.push(po);
break;
case 'P':
case 'p': if(st.isempty())
cout << "stackalready empty\n";
else
{
st.pop(po);
cout << "PO#" << po <<"popped\n";
}
break;
}
cout<< "Please enter A to add a purchaseorder, \n"
<< "Pto process a PO, or Q to quit. \n";
}
cout << "Bye\n";
getchar();
return 0;
}
运行如下: