代码之家  ›  专栏  ›  技术社区  ›  domlao

C++中的结构类成员

c++
  •  0
  • domlao  · 技术社区  · 15 年前

    // 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;
    };
    }
    

    非常感谢。

    2 回复  |  直到 15 年前
        1
  •  1
  •   Flinsch    15 年前

    不,有必要 远期申报 因为你有一个循环依赖。

        2
  •  1
  •   user1115652 user1115652    15 年前

    可以这样做的方法是将CFoo构造函数移动到cpp文件中,然后在Foo.h中类的上面只写 class Impl::FoomImpl; Impl::FoomImpl ,其大小已知(很可能是4个字节)。

    如果您在某个命名空间内,则无需指定作用域。。。

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

    为了避免进一步的混淆,我建议您减少名称空间的数量。除非您正在开发一个将由其他开发人员使用的库,否则即使根本不使用任何库,只要类名是明确的,您的风险也很小。就个人而言,在一个最终用户软件中,我只使用它们来限定枚举的范围,并且我给我的类提供真正清晰和具体的名称。