#include except.h
float *x;
try {x = new float [n];}
catch (xalloc) {
// 仅当new 失败时才会进入 #include except.h
cerr << "Out of Memory" << endl;
exit( 1 ) ;
}
template <class T>
void Make2DArray( T ** &x, int rows, int cols){
// 创建一个二维数组
// 不捕获异常
//创建行指针
x = new T * [rows]; //为每一行分配空间
for (int i = 0 ; i<rows; i++){
x[i] = new int [cols];
}
}
try { Make2DArray (x, r, c);}
catch (xalloc){
cerr<< "Could bot create x" << endl;
exit ( 1 ) ;
}
template <class T>
void Delete2DArray( T ** &x, int rows){
// 删除二维数组x
//释放为每一行所分配的空间
for (int i = 0 ; i < rows ; i++){
delete [ ] x[i];
}
delete [] x; //删除行指针
x = 0;
}
//头文件开始
#ifndef Currency_
#define Currency_
#endif //头文件结尾
public 部分用于定义一些函数(又称方法),这些函数可对类对象(或实例)进行操作,它们
对于类的用户是可见的,是用户与对象进行交互的唯一手段。
private部分用于定义函数和数据成员(如简单变量,数组及其他可赋值的结构),这些函数和数据成员对于
用户来说是不可见的。
借助于public部分和private部分,我们可以使用户只看到他(或她)需要看到的部分,同时把其余信息隐藏起来。
尽管C + +语法允许在public部分定义数据成员,但在软件工程实践中不鼓励这种做法。
class Currency {
public :
// 构造函数
Currency(sign s = plus, unsigned long d = 0, unsigned int c = 0);
//构造函数指明如何创建一个给定类型的对象,它不可以有返回值。与类名相同
// 析构函数
~Currency() {}
bool Set(sign s, unsigned long d, unsigned int c);
bool Set(float a);
sign Sign() const {return sgn;}
unsigned long Dollars() const {return dollars;}
unsigned int Cents() const {return cents;}
Currency Add(const Currency& x) const;
Currency& Increment(const Currency& x);
void Output() const;
private :
sign sgn;
unsigned long dollars;
unsigned int cents;
};
可以采用如下两种方式来创建Currency类对象:
Currency f, g (plus, 3,45), h (minus, 10);
Currency *m = new Currency ( plus, 8, 12);
由于在类定义的内部没有给出函数的具体实现,因此必须在其他地方给出。
Currency::Currency(sign s, unsigned long d, unsigned int c){}
bool Currency::Set(sign s, unsigned long d, unsigned int c){}
bool Currency::Set(float a){}
Currency Currency::Add(const Currency& x) const{}
Currency& Currency::Increment(const Currency& x){}
void Currency::Output () const{}