例如,如果我有一个这样的类:
class Widget {
public:
virtual void Init(); // In this function, call some virtual function
// to construct the object
void Paint(); // Deprecated, use paintWidget instead
void PaintWidget(); // A new implementation of paint
... // Other stuff, including a virtual function
// which need to be called to construct the object
}
Widget
的构建需要一个虚函数调用(这就是我编写 Widget::Init()
的原因)。有没有办法对 Widget::Init()
进行约束,以便在使用对象之前必须调用它,如果用户违反约束,则会引发错误?另一个问题是为已弃用的方法创建自定义警告消息。使用上面的代码,如果我的类(class)的用户调用 Widget::paint()
,我如何告诉他们使用 Widget::paintWidget()
而不是已弃用的 Widget::paint()
,并告诉他们使用已弃用的 ojit_code 的后果?谢谢你。 最佳答案
您问题的第 1 部分:
不,没有好的方法可以使用私有(private)方法提供自定义消息。我要做的是确保您只有一个公共(public) API,它转发到私有(private)实现。这可以通过一些疙瘩模式或通过创建外观来完成。
由于您没有指定某人获取 Widget 的方式,我目前假设是单例。
class Widget {
public:
Widget() : _impl(getHoldOfPrivateWidgetViaSingleton())
{
_impl.init();
}
// ...
private:
PrivateWidget &_impl;
};
// Note: rename of the Widget in your example
class PrivateWidget {
private:
friend class Widget;
PrivateWidget();
// ...
};
这样做的缺点是您将不得不编写一些/大量的转发代码。
您问题的第 2 部分:
class Widget {
public:
void Init();
[[deprecated("use paintWidget instead")]] void Paint();
void PaintWidget(); // A new implementation of paint
...
private:
Widget();
...
}
请注意,如果您无法访问启用了 C++17 的现代编译器,您可能需要查看编译器特定的属性。
关于c++ - 有没有办法自定义编译错误/警告消息?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41661102/