【发布时间】:2018-09-02 05:11:09
【问题描述】:
我有两个类 A,B 我只想从 A 类创建 B 类的对象。我不希望其他类创建 B 类的对象。这里是代码 sn-p。任何建议如何在没有嵌套类的情况下实现?有人可以建议解决这个问题的正确方法是什么吗?
class B
{
public:
B(int x1, int y1, int x2, int y2);
~B();
updateCoordinates(int x1, int y1, int x2, int y2);
private:
int x1;
int y1;
int x2;
int y2;
};
class A
{
public:
A(int mode);
~A();
private:
vector<B> bList;
};
A::A()
{
// Based on the value of mod, create
// objects of B and add to bList
}
【问题讨论】:
-
为什么你不想在
A类中定义类B? -
让
B构造函数private和A成为朋友? -
把整个B类放到A的源文件中,没有其他文件可以使用的header?
-
PassKey idiom 非常适合这种情况
-
在 Live555 Server 代码中,我看到使用了嵌套类。所以,我认为嵌套类也不错。希望得到论坛的意见。
标签: c++