它是简化代码!我有C++文件(在哪里实现)和头文件(在哪里是类定义)!
我有一个文件: Foo.cpp ,它包含了 main.h 。我有 Bar.cpp 文件,该文件使用funcs Foo.cpp 函数,还包括 main.h 。它使用struct来访问Foo对象并调用它的函数。但是struct在 main.h 中定义了吗?我试图这样解决:
**IN MAIN.H**
#pragma once
class Foo;
struct FoobarPackage {
FoobarPackage(Foo *fooObj) {
soso = fooObj;
}
Foo *soso;
};
* * *
**IN FOO.CPP**
#pragma once
#include "main.h"
class Foo {
void doSomething(bool ololo) {
if (ololo) //do something else
}
};
* * *
**IN BAR.CPP**
#pragma once
#include "main.h"
#include "Foo.cpp"
class Bar {
bool killAllHumans(FoobarPackage planet) {
planet.soso->doSomething(true);
return true;
}
};
* * *
但这会导致:
Bar.cpp:8: error: invalid use of incomplete type "struct(WTF??!!! — author's comment) Foo"
main.h:3: error: forward declaration of "struct(why struct?) Foo"
我的代码有什么问题?也不是真正的代码。我简化了我的真实项目,并削减了所有不需要的内容。 Foo.cpp和Bar.cpp当然都有其 header ,用于定义Foo和Bar类,并且在 .cpp 文件中,这只是它们的实现。也是
killAllHumans()
所在的main.cpp调用的main()
。* 已编辑*
我知道
#include
可与 header 一起使用,但我写道它是“伪代码”。我在我的readl项目中使用头文件和cpp文件,并且头中仅包含头和#pragma once
。在这个问题上,我只会简化我的代码!请在回答之前阅读所有问题!* 编辑ED2 *
试图现在编译它。有用。奇怪。
谢谢。
最佳答案
为我工作:
$ cat main.h
#pragma once
class Foo;
struct FoobarPackage {
FoobarPackage(Foo *fooObj) {
soso = fooObj;
}
Foo *soso;
};
$ cat Foo.cpp
#pragma once
#include "main.h"
class Foo {
public:
void doSomething(bool ololo) {
if (ololo) ; //do something else
}
};
$ cat bar.cpp
#pragma once
#include "main.h"
#include "Foo.cpp"
class Bar {
bool killAllHumans(FoobarPackage planet) {
planet.soso->doSomething(true);
return true;
}
};
$ g++ -c bar.cpp
bar.cpp:1:9: warning: #pragma once in main file
$ $ g++ -v
Using built-in specs.
Target: i486-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.4.3-4ubuntu5' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --program-suffix=-4.4 --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-plugin --enable-objc-gc --enable-targets=all --disable-werror --with-arch-32=i486 --with-tune=generic --enable-checking=release --build=i486-linux-gnu --host=i486-linux-gnu --target=i486-linux-gnu
Thread model: posix
gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
$
编辑:正如每个人都指出的那样,该程序仍然存在很多问题。尤其重要的是,
#include
是CPP文件,没有明显的原因。关于c++ - 定义麻烦。 C++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6582950/