c++ - 我能以某种方式使用继承吗

标签 c++ inheritance virtual

您好,我想使用继承类的虚函数,而不必将其包含在最终会进入头文件的类原型(prototype)中。有什么办法吗?

class Base {
public:
    virtual void func () = 0;
};

class Derived : public Base {
public:

};

void Derived::func () {
return;
}

我是这么想的。在我实际使用的情况下,有大量的虚函数我可能会与任何函数一起使用,我不想让所有额外函数的类声明陷入困境。

最佳答案

这对于简单的继承/虚函数是不可能的,但你可以注入(inject)你的 func 实现:

// header file

#include <functional>

class Base {
public:
    Base(std::function<void()> func_impl)
        : m_func_impl{ std::move(func_impl) }
    {
    }

    void func() { m_func_impl(); }

private:
    std::function<void()> m_func_impl;
};

class Derived : public Base {
public:
    Derived();
};

// implementation file

static void Derived_func()
{
    // your implementation of func
}

Derived::Derived()
    : Base{ Derived_func }
{
}

您可以使用 pimpl 习惯用法来完成相同的操作。这避免了每个方法都有一个 std::function,但需要一个二级类层次结构:

// header file

#include <memory>

class Base {
public:
    struct Impl
    {
        virtual ~Impl() {}
        virtual void func() = 0;
    };

    Base(std::unique_ptr<Impl> impl)
        : m_impl{ std::move(impl) }
    {
    }

    void func() { m_impl->func(); }

private:
    std::unique_ptr<Impl> m_impl;
};

class Derived : public Base {
public:
    Derived();
};

// implementation file

class Derived_Impl : public Base::Impl
{
    virtual void func() override
    {
        // your implementation of func
    }
};

Derived::Derived()
    : Base{ std::unique_ptr < Impl > {new Derived_Impl} }
{
}

这两种解决方案都有其缺点,最明显的是实现不在派生类中,因此您必须考虑如何解决范围问题(例如,在您的实现中访问派生类的私有(private)成员)。

关于c++ - 我能以某种方式使用继承吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25581891/

相关文章:

c++ - 使用多态性根据用户输入调用函数

.net - 在 .NET 中编写虚拟打印机

c++ - 使用 C++,如何从派生类方法调用基类方法并将其应用于作为参数传递的对象?

c++ - 如果我在明确的情况下使用指针,编译器可以内联虚函数吗?

java - 如何将一个类中的对象分配给另一个类以及如何计算 ArrayList 中的 double 和 int?

c++ - No matching error operator error in string input?

c++ - 在派生模板类中使用条件类型特征覆盖基类中的虚拟方法

c++ - C++中虚函数的概念?

Python抽象属性和继承

c++ - 在 std 命名空间中重载(非特化)模板