2016-05-14 122 views
1

我有一些C++代码可以在Visual Studio 2013中很好地编译,但不会在使用g ++(无IDE)的linux中编译。Linux上的代码编译失败,在Windows上成功:原因/修复?

什么是造成差异,我怎样才能使代码在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 

回答

3

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

typedef class IApp; 

然后这个模板方法应该被定义出来的行,下面​​:

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

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

最后,这是没有意义的:

virtual void foo() = 0; 

因为同一类有它自己的类类型的static成员,所以需要实例化。但是你已经用纯虚拟函数来阻止它。

GCC有权不编译此代码。

1

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

相关问题