【问题标题】:Code Compilation Fails on Linux, Succeeds on Windows: Cause/Fix?代码编译在 Linux 上失败,在 Windows 上成功:原因/修复?
【发布时间】:2016-05-14 03:59:12
【问题描述】:

我有一些 c++ 代码可以在 Visual Studio 2013 中正常编译,但不能在使用 g++(无 IDE)的 linux 中编译。

造成差异的原因是什么?如何使代码在 linux 上编译?是因为它们是不同的编译器吗?我需要特定的编译器设置吗?

代码:

#include <iostream>

typedef class IApp;
typedef class Component;

class Component
{
public:

protected:
    IApp* app;

    template<typename T>
    void registerEvent()
    {
        app->logEvent();
    }
};

class IApp : protected Component
{
public:
    static IApp NULL_APP;

    void logEvent()
    {
        printf("Event Logged\n");
    }

protected:
    virtual void foo() = 0;
};


int main(int argc, char** argv)
{
    printf("Alive\n");
    system("pause");
    return 0;
}

在 Windows 上,我没有收到编译器错误。在 linux 上,我得到以下编译器错误:

g++ - o res main.cpp - std = c++11
main.cpp:3 : 15 : warning : ‘typedef’ was ignored in this declaration[enabled by default]
typedef class IApp;
^
main.cpp:4 : 15 : warning : ‘typedef’ was ignored in this declaration[enabled by default]
typedef class Component;
^
main.cpp: In member function ‘void Component::registerEvent()’ :
main.cpp : 16 : 6 : error : invalid use of incomplete type ‘class IApp’
app->logEvent();
^
main.cpp:3 : 15 : error : forward declaration of ‘class IApp’
typedef class IApp;
^
main.cpp: At global scope :
main.cpp : 23 : 14 : error : cannot declare variable ‘IApp::NULL_APP’ to be of abstract type ‘IApp’
static IApp NULL_APP;
^
main.cpp:20 : 7 : note : because the following virtual functions are pure within ‘IApp’ :
class IApp : protected Component
    ^
    main.cpp : 31 : 15 : note : virtual void IApp::foo()
    virtual void foo() = 0;
^
make: ***[all] Error 1

【问题讨论】:

    标签: c++ linux windows compilation


    【解决方案1】:

    在这里你应该简单地删除typedef

    typedef class IApp;
    

    那么这个模板方法应该是外联定义的,在IApp下面:

    template<typename T>
    void registerEvent()
    {
        app->logEvent();
    }
    

    否则,它看不到需要取消引用的IApp 的声明。

    最后,这没有意义:

    virtual void foo() = 0;
    

    因为同一个类有一个自己类类型的static成员,所以需要实例化它。但是你已经用纯虚函数防止了这种情况。

    GCC 不编译这段代码是对的。

    【讨论】:

      【解决方案2】:

      在前向类声明之前省略 typedef 关键字,它们不是必需的。只上课 MyClass;对于前向声明就足够了。另一个问题是 foo() 是纯虚拟的——如果你想实例化类,你需要实现它。我很惊讶微软的编译器没有抱怨,但那是微软。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-01
        • 1970-01-01
        相关资源
        最近更新 更多