【问题标题】:C++ class hierarchyC++ 类层次结构
【发布时间】:2013-05-29 07:19:00
【问题描述】:

请先看代码:

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() 能够访问BMfont,而BMstring 内没有任何BMfont 实例。


如果我这样做会怎样:

class BM_FONT_CALL BMstring : public std::string
{

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

public:

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

}

通过使Compile() 成为BMfont 的成员。 但这不会编译。我怎样才能做到这一点?

【问题讨论】:

    标签: c++ class class-hierarchy


    【解决方案1】:

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

    【讨论】:

    • 能否提供示例源代码?我没明白。请再看一遍帖子,我做了修改。
    • 好的,我现在明白了。我之所以从std::string 派生BMstring 是因为我想重写std::string 的赋值运算符并将Compile() 函数放在那里。通过引用BMfont 我不能这样做text = "some string";
    • 在这种情况下,您可能需要字符串可以使用的“默认”字体,这可能是您的 BMString 函数可以访问的 BMFont 或 BMString 的静态成员。
    【解决方案2】:

    据我了解,您想做这样的事情:

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多