参考自d程序设计语言---我的博客http://my.oschina.net/u/218155/blog?fromerr=SwOkb7Sw fllow me
d语言的类,同所有的支持oop的语言一致,只是有一点点差别
类的一些基本属性
enum,static变量,他们初始化一次后不可改变
支持普通的方法
构造器语法 为this()和 ~this()
也支持静态构造器 static this() static ~this()
final可以定义不可覆盖的类
类也支持property方法
this() 的执行顺序是: 分配内存,初始化,冠名,构造函数的调用
~this()的步骤 对象冠名后是活的。所有引用消失,检查是否可以回收,某个时间点回收,释放已解除分配的对象
完整的例子
import std.stdio;
class CrawlerParser {
enum my_flate = 2;
static immutable defualtOpt = "byCurl";
string currentOpt = defualtOpt;
uint catchTime,catchWait;
static CrawlerParser instance;
static int test_static ;
static this(){
//instance = new CrawlerParser;
test_static = 11;
}
static string getDefualtOpt(){
return defualtOpt;
}
uint getCatchTime(){
return catchTime;
}
uint getCatchWait(){
return catchWait;
}
final void runFinal(){
writeln("run final");
}
string crawlerIt(){
return "crawler";
}
this(uint catchTime){
//this.catchTime = catchTime;
this(catchTime,uint.init);
}
this(uint catchTime,uint catchWait){
this.catchTime = catchTime;
this.catchWait = catchWait;
}
CrawlerParser func(){
//this = new CrawlerParser();
return this;
}
this() {
}
~this(){
writeln("free data");
}
static ~this(){
writeln("static free data");
}
}
/*
class XMLCrawlerParser : CrawlerParser{
this(){
}
override void crawlerIt(){
writeln("crawler it");
}
}*/
unittest{
//define d
auto cp = new CrawlerParser();
assert(CrawlerParser.getDefualtOpt() == "byCurl");
cp.catchTime = 3;
assert(cp.getCatchTime() == 3);
//d object refence
auto cp2 = cp;
cp.catchTime = 4;
assert(cp.getCatchTime() == 4);
CrawlerParser cp3 = new CrawlerParser();
assert(cp3 !is null);
cp3.catchTime = 5;
assert(cp.getCatchTime() == 4);
//this() 分配内存,初始化,冠名,构造函数的调用
CrawlerParser cp4 = new CrawlerParser(1);
assert(cp4.getCatchTime() == 1);
assert(cp4.getCatchWait() == 0);
//~this()的步骤 对象冠名后是活的。所有引用消失,检查是否可以回收,
//某个时间点回收,释放已解除分配的对象
destroy(cp2);
assert(cp2 !is null);
assert(cp !is null);
//static this
assert(CrawlerParser.test_static == 11);
//static this的调用顺序是先引入线调用,析构函数相反
//XMLCrawlerParser xcp = new XMLCrawlerParser;
//assert(CrawlerParser.crawlerIt()== "crawler");
//xcp.crawlerIt();
}