如何重用已经具有 main 方法的文件中的类?例如,我想在我自己的程序 main.cpp 中使用另一个开发人员在 foo.cpp 中编写的 struct foo:
//-- foo.cpp --
struct foo {
int bar;
};
int main() {
return 0;
}
//-- end foo.cpp --
//-- main.cpp --
#include "foo.cpp"
int main() {
foo f;
f.bar = 1;
return f.bar;
}
//-- end main.cpp
main.cpp 不会使用 g++ 4.4.4 编译,给出错误:
main.cpp: In function "int main()":
main.cpp:2: error: redefinition of "int main()"
foo.cpp:4: error: "int main()" previously defined here
我无法从 foo.cpp 中提取 main 方法,因为我不控制该代码。在我正在处理的实际代码库中,struct foo 更复杂,所以我不能将它复制到 main.cpp,因为它是不可维护的。