我正在想办法如何安排一些课程。这就是我到目前为止所得到的......
继承层次结构的顶层(自然)是 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 帖子中问了太多反问句?
提前致谢,
Mike
是的,这是可能的。常见的做法是使用以下代码片段:
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 文件中,但随后您必须为每个可能的接口显式实例化它。在 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>;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)