【问题标题】:Interfaces and public methods接口和公共方法
【发布时间】:2017-06-08 05:33:28
【问题描述】:

我有一个使用纯抽象接口的结构(只有公共方法,它们都是=0),一个隐藏实现细节的抽象类和两个继承自它的子类。

我想在这些子类中公开一些公共方法,因为它们仅在该上下文中才有意义,但将它们标记为公共不起作用,因为编译器似乎只能在接口中看到公共方法。如何使子类中的公共方法可访问?

更新

界面:

class Result {
public:
    virtual ~Result() noexcept = default;

protected:
    Result() = default;
};

抽象类:

template <typename T>
class AbstractResult : public Result {
public:
    AbstractResult();
    virtual ~AbstractResult() noexcept = default;
};

第一个孩子:

class AResult : public AbstractResult<PGResult> {
public:
    PGResult() = default;
    virtual ~PGResult() noexcept = default;

    void add_server_status(const char status) noexcept;
    void add_command_complete(const CommandComplete command_complete) noexcept;
    void add_columns(const vector<Column> columns) noexcept;
    void add_error(const Error error) noexcept;
    void add_notification(const Notification notification) noexcept;
};

我想创建一个Result 的实例并在其上调用add_columns(...),这是编译器禁止的:

unique_ptr<Result> result.reset(new AResult);
result->add_columns(...)

【问题讨论】:

  • 你能展示一些你的代码作为参考吗?
  • 调用代码必须使用dynamic_cast 将接口引用转换为派生类引用(并容忍异常),然后调用派生类上的方法。 (您也可以动态转换指针 - 您必须检查 nullptr 的结果)
  • 你能详细说明为什么你有一个抽象类继承自一个具体类吗?这不是 C++ 中的典型模式。通常,您的抽象接口将为所有实现定义一个最小但完整的接口,无需知道已创建哪个实现。
  • @MarkB 我希望界面尽可能干净,只使用公共方法。然后我有一个抽象类,我在其中保留实现通用的代码。我为此使用 CRTP。
  • 当创建一个完整且可用的对象需要的不仅仅是调用它的构造函数时,它是一个字符串标志你需要一个工厂。

标签: c++ oop c++11 inheritance polymorphism


【解决方案1】:

在我看来,当您创建它时您就知道类型,所以在将其分配到 unique_ptr 之前将其隐藏起来:

std::unique_ptr<AResult> temp(new AResult);
temp->add_columns(...);
unique_ptr<Result> result(std::move(temp));

【讨论】:

  • 如果add_columns 抛出异常,则表示内存泄漏。我认为temp 最好输入unique_ptr&lt;AResult&gt;,然后将其移至结果。
  • 好点,忘记了异常安全 - 建议采纳。
  • @ChrisDrew add_columns 是 noexcept ,代码只是将一列添加到向量中。你是说在这种情况下组合会是一个更好的解决方案吗?
  • @ruipacheco 我只是说最好避免原始拥有指针并使用 unique_ptr 管理 temp,就像 Mark 在他的编辑中所做的那样。
  • 对不起,现在才看到这个动作。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-26
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2010-11-05
  • 1970-01-01
相关资源
最近更新 更多