c++ - Linux编译代码失败,Windows编译成功 : Cause/Fix?

标签 c++ linux windows compilation

我有一些 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

最佳答案

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

typedef class IApp;

那么这个模板方法应该在 IApp 下定义为外联:

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

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

最后,这没有意义:

virtual void foo() = 0;

因为同一个类有一个属于自己类类型的static成员,所以需要对其进行实例化。但是您已经使用纯虚函数阻止了这种情况。

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

关于c++ - Linux编译代码失败,Windows编译成功 : Cause/Fix?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37222357/

相关文章:

c++ - OSX 上的 Eclipse C++ 无法构建

c++ - 如何根据类模板参数专门化成员函数

c++ - 找出 C/C++ 程序的运行时间

c - copy_from_user是否修改用户指针?

windows - Crontab 不能在 Windows 上的 Ubuntu 上使用 Bash

python - 子进程调用 ls 时出错

c++ - 在 OpenCV 中使用 Mat 时的 exc_bad_access 虽然看起来我的索引是正确的

Java内存映射文件和交换

linux - 使用 linux shell 命令比较两个文件的数字并找出差异

php - 尝试在 Windows 上使用 MAMP 在 php 中安装 mongodb