简体   繁体   中英

struct class member in C++

Im new and learning C++, is this code a valid C++ implementation, please see code below,

// FoomImpl.h
#include "Foo.h"

namespace FooFoo { namespace Impl {

class FooImpl
{
   public:
      FooImpl( FooFoo::CFoo::stBar bar )
      {
         m_bar = bar;
      }

   private:
      FooFoo::CFoo::stBar m_bar;
};

} }

// Foo.h
#include "FoomImpl.h"

namespace FooFoo {

class CFoo
{
 public:
    struct stBar
    {
       int aBar;
    };

 public:
    CFoo( stBar bar ) : impl(NULL)
    {
       impl = new FooFoo::Impl::FoomImpl( bar );
    }

    CFoo( ) : impl(NULL){}
    ~CFoo( )
    {
       if(impl)
         delete impl;
    }

 private:
    FooFoo::Impl::FoomImpl *impl;
};
}

Many thanks.

不,由于您具有循环依赖性,因此需要前向声明

You cannot have two different objects holding each other on the stack, because when the compiler goes through the header file of an object it needs to now the size of all it's data members in order to know the size of the object itself. Obviously in your case that is not possible.

The way you can do this is move your CFoo constructor in a cpp file, and then in Foo.h above the class just write class Impl::FoomImpl; . This is called a forward declaration. It just tells the compiler that this is a class name. This is enough to use a pointer to that class. Now Foo.h no longer needs to include FoomImpl.h, because it only uses a pointer to Impl::FoomImpl , which is of a known size (most likely 4 bytes).

If you are inside a certain namespace, no need to specify the scope...

namespace FooFoo
{
   //no need to use "FooFoo::" here
}

In order to avoid further confusion I would suggest you keep the number of namespaces down. Unless you are developing a library that will be used by other developers, you risk little even by using none at all, as long as your class names are unambiguous. Personally, in an end user software I only use them to scope enums and I give really clear and specific names to my classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM