c++ - 在继承层次结构中将接口(interface)与实现分离(C++ 新手)

标签 c++ c++11

我正在想办法安排一些类(class)。这就是我到目前为止所得到的...

继承层次的顶端(自然地)是T:

(T.h)
namespace foo
{
    class T
    {
    public:
        virtual void method1(std::string a_parameter) = 0;
        virtual void method2() = 0;
    };
}

我有两个 T 的子类和一些额外的方法 - 这里是 头文件:

(A.h)
namespace foo
{
    class A : public T
    {
    public:
        virtual ~A() {};
        virtual void method3() = 0;
        //and a factory function
        static A* gimmeAnAyy();
    };
}

(B.h)
namespace foo
{
    class B : public T
    {
    public:
        virtual ~B() {};
        virtual void method4() = 0;
        //and a factory function
        static B* gimmeABee();
    };
}

实现类在各自的 .cpp 文件中:

(A.cpp)
namespace foo
{
    class AImpl : public A
    {
    public:
        A(std::string member_data) : m_member_data(member_data) {};
        ~A() {};
        void method3()
        {
            //something really important, can't think of it right now ;-)
        };
    private:
        std::string m_member_data;
    };
    A* A::gimmeAnAyy()
    {
        return new AImpl("this is an impl of A");
    }; 
}

(B.cpp)
namespace foo
{
    class BImpl : public B
    {
    public:
        B(std::string other_data) : m_other_data(other_data) {};
        ~B() {};
        void method4()
        {
            //something really important, can't think of it right now ;-)
        };
    private:
        std::string m_other_data;
    };
    B* B::gimmeABee()
    {
        return new BImpl("this is an imll of B");
    }; 
}

现在编译器提示 - 正确地 - 关于虚函数 我还没有在 AImpl 和 BImpl 中实现的 method1() 和 method2()。

我想要的是一个AImpl和BImpl都可以继承的TImpl类 这样我就不必在两个不同的 .cpp 文件中实现 method1() 和 method2()。

这可能吗?我出去吃午饭了吗?我是否为 StackExchange 帖子问了太多反问?

提前致谢

迈克

最佳答案

是的,这是可能的。通常的做法是使用以下代码段:

template<typename Interface>
class TImpl : public Interface
{
public:
    virtual void method1(std::string a_parameter) { /* implementation */ }
    virtual void method2() { /* implementation */ }
};

然后继承如下:

class Aimpl : public TImpl<A>
{
public:
    virtual void method3() { /* implementation */ }
};

class Bimpl : public Timpl<B>
{
public:
    virtual void method4() { /* implementation */ }
};

您可以将 Timpl 的实现放在 cpp 文件中,但是您必须为每个可能的接口(interface)显式实例化它。这是在 cpp 中按如下方式完成的:

template<typename Interface>
void Timpl<Interface>::method1(std::string a_parameter)
{
    /* implementation */
}

template<typename Interface>
void Timpl<Interface>::method2()
{
    /* implementation */
}

template class Timpl<A>;
template class Timpl<B>;

关于c++ - 在继承层次结构中将接口(interface)与实现分离(C++ 新手),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18478035/

相关文章:

c++ - 未显示消息框

c++ - 如何防止在多个 vector 中添加一个对象?

c++ - 将传递引用转换为传递返回

c++ - 通过 std::reference_wrapper 行为不一致的纯虚函数的运行时多态调用

C++:将一个部分特化设置为等于另一个

javascript - javascript 中的闭包是否与 C++ 中的类实例(具有私有(private)成员和公共(public)方法)相当?

c++ - 如何用 std vector 初始化 std 堆栈?

c++ - 编码风格 - 在 NULL 检查内部 if 条件后在指针上调用方法

c++ - 检测表单中任何小部件的状态是否已更改

c++ - 随机数生成器,C++