我有一个A看起来像这样的课程:
class A {
// A's internal state
public:
void someMethod();
void anotherMethod();
};
Run Code Online (Sandbox Code Playgroud)
我想A在另一个班级里面使用B.我不想B成为一个子类型A,但我想要A以某种形式访问B用户的公共方法.
实现此目的的一种方法是简单地包含A以下公共成员的实例B:
class B {
public:
A a;
// other members
};
Run Code Online (Sandbox Code Playgroud)
另一个是A成为私人成员B,并提供围绕A公共方法的包装:
class B {
A a;
public:
void someMethod(){ a.someMethod(); }
void anotherMethod(){ a.anotherMethod(); }
}
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一种"首选"方式(或者甚至可能不涉及上述两种替代方案),或者只是一个偏好问题.谢谢.
另一种方法是:
class B : private A
{
public:
using A::someMethod;
using A::anotherMethod;
};
Run Code Online (Sandbox Code Playgroud)