有没有办法创建驻留在另一个类中的类的实例

Is there a way you can create an instance of a class that resides within another class?

本文关键字:另一个 实例 创建 有没有      更新时间:2023-10-16

有没有办法创建一个驻留在另一个类中的类的实例?例如:

class foo
{
public:
    foo()
    {
        //Constructor stuff here.
    }
    class bar
    {
       bar()
       {
           //Constructor stuff here.
       }
       void action(foo* a)
       {
           //Code that does stuff with a.
       }
    }
    void action(bar* b)
    {
        //Code that does stuff with b.
    }
}

现在我只想在我的 main() 中创建一个 bar 实例,如下所示:

foo* fire;
bar* tinder;

但 bar 未在此范围内声明。我在类中使用类的原因是因为它们都使用将另一个类作为参数的方法,但我需要在 main() 中为每个类创建一个实例。我能做什么?

您可以使用范围解析运算符:foo::bar* tinder; 。这将给你一个指向bar的指针,而不是一个bar对象。如果你想要那个,你应该做foo::bar tinder.

但是,您没有充分的理由使用嵌套类。您应该将一个放在另一个之前,然后使用前向声明。像这样:

class foo; // Forward declares the class foo
class bar
{
   bar()
   {
       //Constructor stuff here.
   }
   void action(foo* a)
   {
       //Code that does stuff with a.
   }
};
class foo
{
public:
    foo()
    {
        //Constructor stuff here.
    }
    void action(bar* b)
    {
        //Code that does stuff with b.
    }
};

现在我只想在我的 main() 中创建一个柱线实例......

这是您将如何做到这一点:

int main()
{
  foo::bar tinder;
}

barfoo范围内声明。目前尚不清楚为什么会这样,因此除非您有充分的理由,否则不要使用嵌套类。另请注意,您尝试声明指向foofoo::bar的指针,而不是实例。

类栏在类 foo 的范围内声明。所以你必须写

foo::bar* tinder;

此外,您忘记在类栏和foo的定义之后放置分号:)

嵌套类在另一个类的作用域内声明。因此,要从 main 使用它们,您需要告诉编译器在哪里可以找到该类。

这是语法:

foo::bar *tinder;

foo是父作用域,bar嵌套类。

希望它有帮助

你想要的是一个所谓的"嵌套类"。

你可以在这里找到你想知道的一切:为什么在C++中使用嵌套类?

例如:

class List
{
    public:
        List(): head(NULL), tail(NULL) {}
    private:
        class Node
        {
          public:
              int   data;
              Node* next;
              Node* prev;
        };
    private:
        Node*     head;
        Node*     tail;
};