gpt4 book ai didi

c++ - 使用 C++ 子类实例作为默认参数?

转载 作者:太空狗 更新时间:2023-10-29 23:38:11 28 4
gpt4 key购买 nike

因此我定义了几个类:

class StatLogger {
public:
StatLogger();
~StatLogger();

bool open(<parameters>);

private:
<minutiae>
};

还有一个从它派生出来的子类来实现一个空对象模式(未打开它是它自己的空对象)

class NullStatLogger : public StatLogger {
public:
NullStatLogger() : StatLogger() {}
};

然后我有第三个类,我想在它的构造函数中使用一个可选的记录器实例:

class ThirdClass {
public:
ThirdClass(StatLogger& logger=NullStatLogger());
};

我的问题是当我像上面那样做时,我得到:

error: default argument for parameter of type ‘StatLogger&’ has type ‘NullStatLogger’

如果我在定义中进行显式转换,我会得到:

error: no matching function for call to ‘StatLogger::StatLogger(NullStatLogger)

提示没有来自 NullStatLogger 的构造函数,即使它是一个子类。我在这里做错了什么,这在 C++ 中允许吗?

最佳答案

如果您想使用继承和多态性,ThirdClass 需要使用指针或对 StatLogger 对象的引用,而不是实际对象。同样,在这种情况下,您几乎肯定需要将 StatLogger::~StatLogger() 设为虚拟。

例如,修改如下,代码应该编译干净:

class StatLogger {
public:
StatLogger();
virtual ~StatLogger();

// bool open(<parameters>);

private:
// <minutiae>
};

class NullStatLogger : public StatLogger {
public:
NullStatLogger() : StatLogger() {}
};

class ThirdClass {
StatLogger *log;
public:
ThirdClass(StatLogger *logger=new NullStatLogger()) : log(logger) {}
};

编辑:如果您更喜欢引用,代码如下所示:

class StatLogger {
public:
StatLogger();
virtual ~StatLogger();

// bool open(<parameters>);

private:
// <minutiae>
};

class NullStatLogger : public StatLogger {
public:
NullStatLogger() : StatLogger() {}
};

class ThirdClass {
StatLogger &log;
public:
ThirdClass(StatLogger &logger=*new NullStatLogger()) : log(logger) {}
};

关于c++ - 使用 C++ 子类实例作为默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2148967/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com