2013-05-29 231 views
0

请参阅第一代码:C++类层次结构

class BM_FONT_CALL BMfont 
{ 
public: 

BMfont(); 
~BMfont(); 

bool Load(const std::string& fontName); 
void Print(float x, float y); 

class BM_FONT_CALL BMstring : public std::string 
{ 

public: 

    BMstring() { } 
    BMstring(const char* str); 

    BMstring& operator=(const char* str); 
    BMstring operator+=(const char* str); 

private: 

    void Compile(); 

}; 

public: 

BMstring text; 
float scale; 
_uint32 tabSize; 
_uint32 textureSheet; 
_uint32 backTexture; 
_uint32 frontTexture; 
bool enableMasking; 

_uint32 base; 
_uint32 lineHeight; 
_uint32 pages; 
_uint32 scaleW, scaleH; 
_uint32 kerninfo_count; 

BMkerninfo *kerninfo; 
BMchar  chars[MAX_CHAR]; 

private: 

std::string _fontName; 

}; 

我该怎么办BMstring不得不BMfont访问的成员,如果BMstring不会继承BMfont的成员?例如,如果我这样做:

BMfont::BMstring text; 
text.scale //I don't want this 

我想在这里做的是,我希望BMstring::Compile()有与BMfontBMstring没有任何实例BMfont的访问。


或者,如果我这样做:

class BM_FONT_CALL BMstring : public std::string 
{ 

    std::function<void (void)> func; 

public: 

    BMstring() { func = BMfont::Compile(); } 

} 

按制造BMfontCompile()成员。 但这不会编译。我怎样才能做到这一点?

回答

0

最简单和最干净的方法是在BMString中引用一个引用,并将其传递给构造函数或编译方法。如果没有参考,BMfont和BMstring对象将不得不在内存中耦合,每个字体只有一个字符串 - 这肯定是不希望的。

+0

你能提供的示例源代码?我没有明白。请再看看帖子,我做了一个修改。 – mr5

+0

好吧,我现在明白了。我从'std :: string'派生'BMstring'的原因是因为我想重写'std :: string'的赋值操作符,并在其中放置了'Compile()'函数。并且通过引用'BMfont',我不能这样做'text =“some string”;' – mr5

+0

在这种情况下,您可能需要一个字符串可以使用的'默认'字体,这可以是BMFont的静态成员或您的BMString函数可以访问的BMString。 – matt

0

据我了解你想要做这样的事情:

class C{ 
public: 
    C() : nested(*this) 
     { 
     } 

    void callNested() 
     { 
      nested.callOuter(); 
     } 

private: 
    class N{ 
    public: 
     N(C &c) : outer(c) 
      { 
      } 

     void callOuter() 
      { 
       outer.OuterFunc(); 
       // you have access to any C's member through outer 
       // reference 
      } 

    private: 
     C &outer; 
    }; 

    N nested; 

    void OuterFunc() 
     { 
     } 
}; 

int main() 
{ 
    C c; 
    c.callNested(); 
}