D 的方式
属性可以使用正常的域语法 get 和 set,然后 get 和 set 会被编译器用方法调用取代。
class Abc
{
void property(int newproperty) { myprop = newproperty; } // set
int property() { return myprop; } // get
private:
int myprop;
}
使用时:
Abc a;
a.property = 3; // 等价于 a.property(3)
int x = a.property; // 等价于 int x = a.property()
因此,在 D 中属性可以被看作一个简单的域名。开始时,属性可以只是一个简单的域名,但是如果后来需要将读取和设置行为改变为函数调用,只需要改动类的定义就够了。这样就避免了定义 get 和 set 时敲入冗长的代码,仅仅是为了‘谨防’日后派生类有可能会不得不重载它们。这也是一种定义接口类的方法,这些类没有数据域,只在语法上表现得好像它们作了实际工作。
递归模板
C++ 的方式
一种使用模板的高级方式是递归的扩展它们,依靠特化来终止递归。用来计算阶乘的模板可能会是这样:
template<int n> class factorial { public: enum { result = n * factorial<n - 1>::result }; }; template<> class factorial<1> { public: enum { result = 1 }; }; void test() { printf("%d/n", factorial<4>::result); // 打印出 24 } |
D 的方式
D 的版本与之相似,但是简单一点,利用了将单一模板成员提升到外围的名字空间的能力:
template factorial(int n) { enum { factorial = n* .factorial!(n-1) } } template factorial(int n : 1) { enum { factorial = 1 } } void test() { printf("%d/n", factorial!(4)); // 打印出 24 } |