【问题标题】:Is there a way you can create an instance of a class that resides within another class?有没有一种方法可以创建驻留在另一个类中的类的实例?
【发布时间】:2014-03-25 09:39:26
【问题描述】:

有没有一种方法可以创建驻留在另一个类中的类的实例? 例如:

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() 中每个类的实例。我能做什么?

【问题讨论】:

  • 在类定义后缺少分号。

标签: c++


【解决方案1】:

您可以使用范围解析运算符: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.
    }
};

【讨论】:

  • 太棒了。你刚刚教会了我一些新的有用的东西。
  • 请注意,您不能在 foo 的定义之前使用 a。相反,在 foo 之后定义该成员。 class bar {public: bar() {...} inline void action(foo *a);}; 之后:void bar::action(foo *a) {...}
  • 这回答了我的下一个问题。
【解决方案2】:

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

你会这样做:

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

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

【讨论】:

    【解决方案3】:

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

    foo::bar* tinder;
    

    你也忘了在类 bar 和 foo 的定义之后放置分号。:)

    【讨论】:

      【解决方案4】:

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

      语法如下:

      foo::bar *tinder;
      

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

      希望对你有帮助

      【讨论】:

        【解决方案5】:

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

        你可以在这里找到你想知道的一切:Why would one use nested classes in C++?

        例如:

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

        【讨论】:

        • 我已经在使用嵌套类,这是我的问题的一部分。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多