c++ - 接口(interface)和公共(public)方法

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

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

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

更新

接口(interface):

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

protected:
    Result() = default;
};

抽象类:

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

第一个 child :

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(...)

最佳答案

在我看来,当你创建它时你就知道它的类型,所以在将它分配给 unique_ptr 之前先把它藏起来:

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

关于c++ - 接口(interface)和公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41810902/

相关文章:

c++ - 为什么 vector::push_back 有两个重载?

machine-learning - liblbfgs 在 C++ 中编译

c++ - 绘图框架

javascript - 在 JavaScript 中通过字符串调用函数

c++ - 如何在不破坏现有客户端代码(pre c++17)的情况下将类转换为模板类?

c++ - 使用 constexpr 数组与 const 数组的元素来实例化模板

c++ - RapidXML 以深度优先模式解析 XML

c++ - 虚函数是在编译期间确定的吗?

java - 从另一个类混淆调用方法(机器人类)

python - 将类的所有实例存储在类字段中是否不好?