【问题标题】:forward declaring with inheritance information带有继承信息的前向声明
【发布时间】:2011-06-10 02:50:34
【问题描述】:

这编译得很好,虽然我还不想尝试运行它。不过……

//class base;
//class derived;
//class derived : public base;

class base {};
class derived : public base {};

class other
{
    public:
        void func() {base1 = derived1;}
        base* base1;
        derived* derived1;
};

void main()
{
}

... 将其他类移到基类和派生类的定义之上,我必须在 myne 的程序中做类似的事情会导致编译错误。

显而易见的解决方案是在代码顶部前向声明基和派生显示注释掉,但这会导致无法在基*和派生*之间转换错误。尝试转发包含继承信息的声明也不起作用。

【问题讨论】:

    标签: c++ forward-declaration base derived


    【解决方案1】:

    这应该可行。你需要把其他人向上移动

    但是在下面声明函数。这样 func 就能够“看到”derived 是 base 类型。

    例如,

    class base;
    class derived;
    //class derived : public base;
    
    class other
    {
        public:
            void func();
            base* base1;
            derived* derived1;
    };
    
    class base {};
    class derived : public base {};
    
    void other::func() { base1 = derived1; }
    

    【讨论】:

    • 优秀。工作得很好,在这个和真正问题的程序中。我希望这将永远解决问题。
    【解决方案2】:

    没有用于前向声明两个类并指定一个继承自另一个的语法。这是因为继承可能很复杂(多重和/或虚拟),因此分配 base1 = derived1 可能涉及一些算术,并且当编译器只知道 derived 继承自 @987654323 时,编译器很难/不可能生成该算术@。

    因此,为了解决您的问题,您可以将func 设为非内联(参见AbstractDissonance 的答案),或者,如果您绝对需要内联,请使用reinterpret_cast

    class base;
    class derived;
    
    class other
    {
        public:
            void func() {base1 = reinterpret_cast<base*>(derived1);}
            base* base1;
            derived* derived1;
    };
    

    这很糟糕,因为 C++ 标准不能保证它可以工作,而且如果您使用多重/虚拟继承,它几乎肯定不会工作。仅当 func 必须尽可能快(即 inline)并且您不需要可移植代码时才使用此选项。

    【讨论】:

    • 我会记住这一点,但现在使用其他解决方案。知道是有用的。我没有意识到 reinterpret_cast 可以这样使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多