2013-05-29 227 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(); 
}