C++ - 在另一个中使用 .cpp 文件?

标签 c++ methods

只是一个简单的问题:是否可以在另一个 .cpp 文件中使用一个 .cpp 文件 - 比如调用它。

例如 文件 1.cpp:

#include < iostream > 
#include < string >
  using namespace std;

void method(string s);

int main()
{
  method("Hello World");
  return 0;
}

void method(string s)
{
  //get this contents from file2.cpp
}

和 File2.cpp:

#include <iostream>

using namespace std;

void method(string s)
{
   cout << s << endl;
}

因此能够按照该思路做一些事情。 所以我不会将我所有的代码都塞进 1 个 cpp 文件中

谢谢。

最佳答案

你需要制作一个头文件;例如 File2.h,您可以在其中放置要重用的每个函数的原型(prototype):

#ifndef FILE2_H_
#define FILE2_H_    

void method(string s);

#endif  /* FILE2_H_ */

然后您需要在 File2.cpp 和 File1.cpp 中包含此 header :

#include "File2.h"

现在在 File1.cpp 中你可以调用这个函数而不用声明它:

int main()
{
  method("Hello World");
  return 0;
}

关于C++ - 在另一个中使用 .cpp 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23086945/

相关文章:

c++ - 返回对 C++ 中动态数组元素的引用?

c++ - "exposition only"是什么意思?为什么要使用它?

javascript - 进行属性别名的最佳方法?

ruby - Ruby 中方法的静态局部变量?

javascript - 为什么当我们调用函数时 IE 不接受括号

C#:我可以像在 C++ 中那样写 "private:"或 "protected:"区域吗

c++ - 在关闭 Occi::Connection 之前复制 Occi::ResultSet

c++ - OpenCV 像素强度

java - Java 接口(interface)有什么用处以及如何处理跨类方法?

java - 静态方法可能包含在类中的 3 种可能情况是什么?