会员复制方法 [英] Copying Methods from Member
问题描述
我有一个简单的低级容器类,由更高级别的文件类使用。基本上,在将最终版本保存到实际文件之前,文件类使用容器在本地存储修改。因此,某些方法直接从容器类传递到文件类。 (例如, Resize()
。)
I have a simple, low-level container class that is used by a more high-level file class. Basically, the file class uses the container to store modifications locally before saving a final version to an actual file. Some of the methods, therefore, carry directly over from the container class to the file class. (For example, Resize()
.)
我刚刚将文件类中的方法定义为调用他们的容器类变体。例如:
I've just been defining the methods in the file class to call their container class variants. For example:
void FileClass::Foo()
{
ContainerMember.Foo();
}
然而,这种情况越来越令人讨厌。有更好的方法吗?
This is, however, growing to be a nuisance. Is there a better way to do this?
这是一个简化的例子:
class MyContainer
{
// ...
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
}
class MyClass
{
MyContainer Member;
public:
void Foo()
{
Member.Foo();
// This seems to be pointless re-implementation, and it's
// inconvenient to keep MyContainer's methods and MyClass's
// wrappers for those methods synchronized.
}
}
推荐答案
好,为什么不直接从 MyContainer
继承,并使用声明公开那些你想要转发的函数?这被称为实施
MyClass
MyContainer
。
Well, why not just inherit privatly from MyContainer
and expose those functions that you want to just forward with a using
declaration? That is called "Implementing MyClass
in terms of MyContainer
.
class MyContainer
{
public:
void Foo()
{
// This function directly handles the object's
// member variables.
}
void Bar(){
// ...
}
}
class MyClass : private MyContainer
{
public:
using MyContainer::Foo;
// would hide MyContainer::Bar
void Bar(){
// ...
MyContainer::Bar();
// ...
}
}
现在外面将能够直接调用 Foo
,而 Bar
只能在 MyClass
中访问。如果现在创建一个具有相同名称的函数,它隐藏了基本功能,你可以像这样包装基本功能。当然,你现在需要完全限定对基本功能的调用,否则你会去进入无休止的递归。
Now the "outside" will be able to directly call Foo
, while Bar
is only accessible inside of MyClass
. If you now make a function with the same name, it hides the base function and you can wrap base functions like that. Of course, you now need to fully qualify the call to the base function, or you'll go into an endless recursion.
此外,如果你想允许(非多态)子类化 MyClass
,这是一个罕见的地方,受保护的遗产实际上是有用的:
Additionally, if you want to allow (non-polymorphical) subclassing of MyClass
, than this is one of the rare places, were protected inheritence is actually useful:
class MyClass : protected MyContainer{
// all stays the same, subclasses are also allowed to call the MyContainer functions
};
如果您的 MyClass
没有,则为非多态的虚拟析构函数。
Non-polymorphical if your MyClass
has no virtual destructor.
这篇关于会员复制方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!