源文件中的嵌套类定义 [英] Nested Class Definition in source file

查看:131
本文介绍了源文件中的嵌套类定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,如果此问题已被问过,我们深表歉意。我搜索了一会儿,但没有找到答案,很可能是因为我不知道如何正确地打字。



如果我有一个类似的嵌套类:

  class MyClass 
{
class NestedClass
{
public:
//嵌套类成员和这里的定义
};

//主类成员这里
};

目前, MyClass 的定义 CPP 文件,但是 NestedClass 的定义在头文件中,也就是说,我不能声明函数/在 CPP 文件中。



所以我的问题是,如何在cpp文件中定义 NestedClass 的函数?如果我不能,原因是什么(如果是这样,我有一个模糊的想法,为什么会发生,但我想要一个很好的解释)?结构怎么样?

解决方案

如果你的内部类有如下方法:

  class MyClass {
class NestedClass
{
public:
void someMethod();
};

//主类成员这里
};

...那么你可以在.cpp文件中定义它,如下:

  void MyClass :: NestedClass :: someMethod(){
// blah
}

结构与C ++中的类几乎相同 - 只是默认为public。

您可以(如注释中所述)只是声明一个内部类,例如:

/ p>

  class MyClass {
class NestedClass;
// blah
};

..然后在实施文件中定义:

  class MyClass :: NestedClass {
// etc.
};


First off, I apologize if this question has been asked before. I searched for a while but did not find the answer, most likely because I don't know how to word it properly. Onto the question.

If I have a nested class like so:

  class MyClass
  {
    class NestedClass
    {
    public:
      // nested class members AND definitions here
    };

    // main class members here
  };

Currently, the definitions of MyClass are in the CPP file but the definitions for NestedClass are in the header file, that is, I cannot declare the functions/constructors in the CPP file.

So my question is, how do I define the functions of NestedClass in the cpp file? If I cannot, what is the reason (and if this is the case, I have a vague idea of why this happens but I would like a good explanation)? What about structures?

解决方案

You can. If your inner class has a method like:

  class MyClass   {
    class NestedClass
    {
    public:
      void someMethod();
    };

    // main class members here
  };

...then you can define it in the .cpp file like so:

void MyClass::NestedClass::someMethod() {
   // blah
}

Structures are almost the same thing as classes in C++ — just defaulting to 'public' for their access. They are treated in all other respects just like classes.

You can (as noted in comments) just declare an inner class, e.g.:

class MyClass   {
    class NestedClass;
    // blah
};

..and then define it in the implementation file:

class MyClass::NestedClass {
  // etc.
};

这篇关于源文件中的嵌套类定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆