我正在玩d,它可以使代码工作而不使用例如auto test1 = new Word(“hello”); ??
import std.stdio;
import std.conv : to;
import std.digest.sha;
import std.algorithm;
class Word {
string thisWord;
this(string fWord) {
thisWord = fWord;
}
string toHex(){
return (cast(ubyte[]) thisWord).toHexString;
}
}
string test(const Word& thisword){
writeln(thisword.toHex)
}
void main() {
test("hello");
}
答案 0 :(得分:3)
您似乎要求C++中的隐式转换。 D只有其中的一小部分 - 语言中有一些默认的隐式转换(int为float,非const为const),alias this用于将您控制的类型转换为其他类型
但是,没有方法可以将某些您无法控制的类型转换为其他类型(例如字符串到类实例)。因为这似乎是你想要的,答案是否定的,D不能这样做。
代码中的其他一些内容:string test(const Word& thisword)
不是D-D类总是引用类型,因此添加C ++&符号是不必要的,也不起作用(D中的引用标有ref
而不是&
)。
另外,考虑一下为什么你想在这种情况下使用类而不是结构 - 大多数D代码使用了很多结构和很少的类,因为D中类的主要吸引力是继承(和第二个吸引力是参考行为)。
答案 1 :(得分:1)
答案是不 - 这是不可能的。某些东西,某处需要实例化Word类型的对象并将其传递给测试(Word)函数。您可以为一个示例添加一个带有字符串的重载函数(包装器)test(string)
,并调用代码中的原始test(Word)
函数。类似的东西:
string test(string arg){
test(new Word(arg);
}