开发者

nested class as a parameter for the member function in C++

I am integrating someone's code, which has everything in one cpp file. The main code is like this:

class Outer
{
public:
   struct Inner
   {
      struct In_inner
      {
         ...
      }
   }
   int func(Inner& inn, Inner::In_inner& in_inn)
   {
      ...
   } 
}

To make separation, should I add th开发者_高级运维e "Outer::" for the "Inner" parameter, as follows?

in the header file

class Outer
{
public:
   struct Inner
   {
      struct In_inner
      {
         ...
      }
   }
   int func(Inner& inn, Inner::In_inner& in_inn);
}

and in the cpp file:

int Outer::func(Outer::Inner& inn, Outer::Inner::In_inner& in_inn)
{
    ...
} 

It sounds a bit weird to me that the parameter list is a bit different from the declaration. Also, can I keep everything in the same file again, and include it as a header file?

Thanks for any comments!


int Outer::func(Outer::Inner& inn, Outer::Inner::In_inner& in_inn)

Yes. You've correctly written this. You've to add Outer:: if you define it outside the class.


It sounds a bit weird to me that the parameter list is a bit different from the declaration

That is okay. The function is defined outside the class. You're no more in the scope of the class. Hence it looks a bit different.

But if you don't want it to look different, then you can write Outer:: in the declaration as well, as shown below:

class Outer
{
public:
   //...
   int func(Outer::Inner& inn, Outer::Inner::In_inner& in_inn);
};

This is fine, and would work because Outer is an injected-name, its available inside the class as well.

struct A
{
    struct B { 
        struct C {};
    };

    B b1;    //okay - as usual
    A::B b2; //this is also okay - not so usual though

    B::C c1;    //okay - as usual
    A::B::C c2; //this is also okay - not so usual though

    A::A::A::A::A::A *pA; //this is very very unsual. But it is also okay!
};

The last line is okay, because the name A is injected inside the definition of class A. Hence it becomes recursively available.

See it compiles fine:

  • http://www.ideone.com/oiy2h


The parameter list isn't different; the types are the same. It's not uncommon to have explicitly qualified std:: members in the header file and use using namespace std; in the source file, either. That's basically the same thing.

It doesn't matter how you qualify the types, as long as they refer to the same types. And because you are not in the scope of Outer in the source file, the explicit qualification is necessary there.


Within the class declaration/definition, you are in the scope Outer::. Outside that (in your .cpp), you are not. Yes, you can keep the function definition in the header: it is an implicit inline.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜