Jes*_*nds 4 arrays pointers d class
我写信给输出的方法来几个输出流一次,我把它树立正确的现在的方式是,我有一个LogController,LogFile并且LogConsole,后两者是的实现Log接口.
我现在正在尝试做的是添加一个方法来LogController附加Log接口的任何实现.
我想怎么做如下:在LogController我有一个关联数组,我存储指向Log对象的指针.当调用writeOut方法时LogController,我希望它然后遍历数组的元素并调用它们的writeOut方法.后者我能做到,但前者证明是困难的.
法师/实用/ LogController.d
module Mage.Utility.LogController;
import std.stdio;
interface Log {
public void writeOut(string s);
}
class LogController {
private Log*[string] m_Logs;
public this() {
}
public void attach(string name, ref Log l) {
foreach (string key; m_Logs.keys) {
if (name is key) return;
}
m_Logs[name] = &l;
}
public void writeOut(string s) {
foreach (Log* log; m_Logs) {
log.writeOut(s);
}
}
}
Run Code Online (Sandbox Code Playgroud)
法师/实用/ LogFile.d
module Mage.Utility.LogFile;
import std.stdio;
import std.datetime;
import Mage.Utility.LogController;
class LogFile : Log {
private File fp;
private string path;
public this(string path) {
this.fp = File(path, "a+");
this.path = path;
}
public void writeOut(string s) {
this.fp.writefln("[%s] %s", this.timestamp(), s);
}
private string timestamp() {
return Clock.currTime().toISOExtString();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过使用attach函数的多个东西,但没有一个.构建失败,并出现以下错误:
Mage\Root.d(0,0): Error: function Mage.Utility.LogController.LogController.attach (string name, ref Log l) is not callable using argument types (string, LogFile)
Run Code Online (Sandbox Code Playgroud)
这是有罪的功能:
public void initialise(string logfile = DEFAULT_LOG_FILENAME) {
m_Log = new LogController();
LogFile lf = new LogFile(logfile);
m_Log.attach("Log File", lf);
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我这里哪里出错了?我很难过,我无法在任何地方找到答案.我尝试了很多不同的解决方案,但都没有.
D中的类和接口是引用类型,因此Log*是多余的 - 删除*.类似地,没有必要使用refin ref Log l- 就像在C++中通过引用获取指针一样.
这是您发布的错误消息的原因 - 通过引用传递的变量必须完全匹配类型.删除ref应解决错误.