C++ 中的包装类
假设我有以下抽象类:
class AbstractClass {
public:
AbstractClass() {}
virtual ~AbstractClass() {}
virtual void virtMethod()
{
printf( "%p\n", this );
}
void method()
{
printf( "%p\n", this );
}
...
};
以及以下子类:
class RawClass : public AbstractClass
{
public:
RawClass();
~RawClass();
...
};
class Wrapper : public AbstractClass
{
public:
Wrapper( AbstractClass* wrapee ) : _wrappee ( wrappee ) {}
~Wrapper() {};
void virtMethod()
{
_wrappee->virtMethod();
}
...
private:
AbstractClass _wrappee;
};
现在,假设我执行以下操作:
RawClass* r = new RawClass();
Wrapper* w = new Wrapper( r );
w->virtMethod(); // This prints the address of r
w->method(); // This prints the address of w
我希望发生的是对 w->method()
的调用表现相同作为对 w->virtMethod()
的调用。但是,如果不将 method()
虚拟化并在仅调用 RawClass::method()
的 Wrapper
中编写它的实现,我就无法做到这一点代码>.
我显然在这里遇到了一些设计问题,但无法找到一种方法来使其工作,同时让 RawClass
和 Wrapper
指定相同的接口。
任何帮助将不胜感激。
Say I have the following abstract class:
class AbstractClass {
public:
AbstractClass() {}
virtual ~AbstractClass() {}
virtual void virtMethod()
{
printf( "%p\n", this );
}
void method()
{
printf( "%p\n", this );
}
...
};
And the following child classes:
class RawClass : public AbstractClass
{
public:
RawClass();
~RawClass();
...
};
class Wrapper : public AbstractClass
{
public:
Wrapper( AbstractClass* wrapee ) : _wrappee ( wrappee ) {}
~Wrapper() {};
void virtMethod()
{
_wrappee->virtMethod();
}
...
private:
AbstractClass _wrappee;
};
Now, say I do the following:
RawClass* r = new RawClass();
Wrapper* w = new Wrapper( r );
w->virtMethod(); // This prints the address of r
w->method(); // This prints the address of w
What I would like to happen is for calls to w->method()
to behave the same as calls to w->virtMethod()
. However, I can't do this without making method()
virtual and writing an implementation of it in Wrapper
which merely calls RawClass::method()
.
I have clearly got some design issues here, but can't figure out a way to get this to work, whilst having RawClass
and Wrapper
prescribe to the same interface.
Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你不应该从 AbstractClass 派生 Wrapper ,而是像 智能指针,以便可以调用 AbstractClass 的方法
并像这样调用它,
Boost 或 C++11 已经为你做到了这一点,如果你使用shared_ptr
I think you should not derive Wrapper from AbstractClass and instead overload
->
operator like a smart pointer so that methods of AbstractClass can be invokedand call it like so
Boost or C++11 already does this for you if you use shared_ptr