gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:16:48 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com