奇技淫巧1

一、宏定义简化类变量的Set,Get函数:

#define vtkSetMacro(name,type) \
virtual void Set##name (type _arg) \
{ \
if (this->name != _arg) \
{ \
this->name = _arg; \
} \
}

#define vtkGetMacro(name,type) \
virtual type Get##name () { \
return this->name; \
}

通过##连接字符串的作用,该宏在类中被展开为与name相关的函数,

在类中使用该宏时,参数name为函数需要设置的变量名,type为该变量的类型。

例:

class myWindow
{
public:

vtkSetMacro(value,int);

vtkSetMacro(x,double);

vtkGetMacro(y,double);


private:

int value;

double x;

double y;

};

则该类编译时自动展开为:

class myWindow 
{
public:
virtual void Setvalue (int _arg) { 

  if (this->value != _arg) 
  { 
  this->value = _arg; 
  } 
}

virtual void Setx (double _arg) { 

  if (this->x != _arg) 
  { 
  this->x = _arg; 
  } 
}

virtual double Gety () { 
  return this->y; 
}


private:

int value;

double x;

double y;

};

上面所示为基本类型的set,get函数示例,通过改写宏定义,可以扩展其他应用情况,

只要函数为简单的赋值以及返回值,输入,输出语句,都可以通过该方法简化,代码较为简洁,避免大量重复编码。

学习自vtkSetGet.h

转载请标明出处

猜你喜欢

转载自www.cnblogs.com/arunz/p/9053839.html