【问题标题】:Alternative to nested class替代嵌套类
【发布时间】: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 构造函数privateA 成为朋友?
  • 把整个B类放到A的源文件中,没有其他文件可以使用的header?
  • PassKey idiom 非常适合这种情况
  • 在 Live555 Server 代码中,我看到使用了嵌套类。所以,我认为嵌套类也不错。希望得到论坛的意见。

标签: c++


【解决方案1】:
class B
{
    friend class A;
    private:
        B(int x1, int y1, int x2, int y2);
    ...
}

【讨论】:

  • 创建对象后,我想将句柄交给另一个对象,以便它可以调用 B 的一个公共函数。我认为这种方法是可能的,不是坏主意
猜你喜欢
  • 1970-01-01
  • 2011-03-27
  • 2013-07-20
  • 2020-12-22
  • 2014-05-08
  • 2019-02-28
  • 2011-07-10
相关资源
最近更新 更多