函数返回值类型的设计(一)

上一篇 / 下一篇  2007-08-16 01:21:55 / 个人分类:FEMRP

      用户自定义数据类型是C++优于C的特征之一,在程序设计中要充分利用这一特点,以便于程序开发和调试.在有限元程序设计中,我们常常遇到一个问题,就是选择函数返回值类型的问题.一般情况,一个函数返回值的类型取决于该函数的功能.比如一个判断函数返回值的类型应该是bool,而一个计算函数返回值的类型可能是double型或double型数组.如果不需返回任何信息,则可以设置为void.

      可在实际程序设计中,单纯一种类型的返回值所表达的信息并不足够丰富.比如,一个计算函数在执行过程中可能产生三种可能:1. 得出期望的计算结果; 2. 由于某些条件限制, 无法全部正常执行; 3. 执行失败.显然,在后两种情况下,仍返回计算结果是不合理的,但函数又要求有返回值.还有一个例子,在有限元程序读入数据时可能遇到多种情况:1. 正确读入期望数据; 2. 数据不合理; 3. 数据不存在. 一个计算函数或数据读入函数返回的信息应该反映函数执行后可能的所有结果.这无论对于程序运行和调试都是非常必要的.

      由此,FEMRP中设计了一种函数返回值类型,称为ERESULT.它负责表达一个函数的执行状态.这实际上是对bool型变量的扩展,在函数出现运行错误时,返回出现错误的出处和性质,以及对错误的描述.

      ERESULT的设计灵感来自于API中对消息tagMSG的定义.通过ERESULT变量可清楚地反映出函数执行是否成功,在执行出错时,异常发生所在的函数以及对该错误的文字描述.下面先给出ERESULT的设计代码.然后再对RESULT的设计细节作进一步解释.

typedef bool FORMAT;
typedef bool PROCESS;
typedef bool NUMBERICAL;
typedef class EOBJECT_RESULT
{
public:

 EOBJECT_RESULT():isProcess(false),isFormat(false),isMumerical(false),format_code(0),value(0){}

 EOBJECT_RESULT( const EOBJECT_RESULT& rhs)
 {
  isProcess   = rhs.isProcess;
  isFormat    = rhs.isFormat;
  isMumerical = rhs.isMumerical;
  format_code = rhs.format_code;
  value       = rhs.value;
  address     = rhs.address;
  description = rhs.description;
 }

 EOBJECT_RESULT& perator = ( const EOBJECT_RESULT& rhs)
 {
  if( this == &rhs)
   return *this;

  isProcess   = rhs.isProcess;
  isFormat    = rhs.isFormat;
  isMumerical = rhs.isMumerical;
  format_code = rhs.format_code;
  value       = rhs.value;
  address  = rhs.address;
  description = rhs.description;

  return *this;
 }


 bool IsOK() {
  if( isProcess || isFormat || isMumerical )
   return true;
  else
   return false;
 }

 void SetAddress( char* infor, double value )
 {
  address.append( "Error File: " );
  address.append( infor );
  address.append( " Error Value: " );
  string t = tostring<double>(value,std::dec);
  address.append(t.c_str());
 }

 string Description() { return description; }

 void SetOk(){
  isProcess   = true;
  isFormat    = true;
  isMumerical = true;
 }

 PROCESS     isProcess;
 FORMAT      isFormat;
 NUMBERICAL  isMumerical;
 int         format_code;   //标识格式错误的种类
 double      value;         //数值
 string      address;
 string      description;
 std::ostringstream oss;

} RES;


TAG:

引用 删除 Guest   /   2008-03-21 16:07:43
5
 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

Open Toolbar