不确定这个名字是否非常有说服力,但现在这样。
我正在连接一个API,该API需要继承基类并定义许多纯虚方法。
对于良好的编程习惯,我希望在不同的(子)类中定义这些方法。
目前,我使用了facade / wrapper(两者兼而有之)类,它继承了基类,实例化了子类,并调用了这些实例化类的必要方法:
#include <cstdio>
class Base
{
public:
virtual void reqImplementation( void ) = 0;
};
class APIImplementation
{
private:
Base * ptr_;
public:
APIImplementation( Base * ptr ) :
ptr_( ptr )
{
ptr_->reqImplementation();
}
};
class MyImplementation
{
private:
APIImplementation * api_;
public:
void reqImplementation( void )
{
printf("Hello World!\n");
}
MyImplementation( APIImplementation * api ) : api_( api ) {}
};
class MyFacade : public Base
{
private:
MyImplementation * my_impl_;
APIImplementation * api_;
void reqImplementation( void )
{
my_impl_->reqImplementation();
}
public:
MyFacade( void )
{
api_ = new APIImplementation( this );
my_impl_ = new MyImplementation( api_ );
}
};
int main( void )
{
MyFacade my_facade;
return 0;
}
有没有办法在这个facade / wrapper中实例化的子类中实现纯虚函数?或者,或者,对于这样的事情,什么是好的做法?我想要类似的东西(我知道它现在显然不起作用):
#include <cstdio>
class Base
{
public:
virtual void reqImplementation( void ) = 0;
};
class APIImplementation
{
private:
Base * ptr_;
public:
APIImplementation( Base * ptr ) :
ptr_( ptr )
{
ptr_->reqImplementation();
}
};
class MyImplementation : public Base
{
private:
APIImplementation * api_;
public:
void reqImplementation( void )
{
printf("Hello World!\n");
}
MyImplementation( APIImplementation * api ) : api_( api ) {}
};
class MyFacade : public Base
{
private:
MyImplementation * my_impl_;
APIImplementation * api_;
public:
MyFacade( void )
{
api_ = new APIImplementation( this );
my_impl_ = new MyImplementation( api_ );
}
};
int main( void )
{
MyFacade my_facade;
return 0;
}
请注意,API源是开放的,因此我可以将这些纯虚拟方法更改为其他任何内容,但是代码非常详尽,所以我的更改比重要的更小。
答案 0 :(得分:0)
如果我找对了你,你需要一个虚拟继承。这是一个例子
#include <iostream>
using namespace std;
// base class with lots of methods (two, actually)
struct Base {
virtual void f() = 0;
virtual void g() = 0;
};
// here's a class with implementation of f
struct ImplementationPart1 : public virtual Base {
virtual void f() {
cout << 4;
}
};
// here's a class with implementation of g
struct ImplementationPart2 : public virtual Base {
virtual void g() {
cout << 2;
}
};
// here's a class with all the implementations
struct Implementation : public ImplementationPart1, public ImplementationPart2 {};
int main() {
// Implementation inherits from Base, yes
Base *x = new Implementation();
// everything works, as expected
x->f();
x->g();
}