简体   繁体   English

调用函数,不同类中的main

[英]Calling function, main in different class

So I have a main.cpp file with a simple hello world program containing a function that prints hello world, and a main method.所以我有一个 main.cpp 文件,其中包含一个简单的 hello world 程序,其中包含一个打印 hello world 的函数和一个 main 方法。 How do I move only the function that prints hello world into a different .cpp file.如何仅将打印 hello world 的函数移动到不同的 .cpp 文件中。 I have a main.cpp, function.cpp and function.h files.我有一个 main.cpp、function.cpp 和 function.h 文件。

I've tried to #include function.h in the function.cpp file but won't work.我试图在 function.cpp 文件中 #include function.h 但不起作用。

// main.cpp
#include <iostream>

std::string funct()
{
    return "hello";
}

int main()
{
    std::cout<<funct()<<std::endl;
    return 0;
}

// function.h
string funct();

//function.cpp
?

It is as simple as就这么简单

// function.h
#include <string>
std::string funct();

// function.cpp
std::string funct()
{
  return "hello"
}

// main.cpp
#include <iostream>
#include "function.h"

int main()
{
  std::cout << funct() << "\n";
  return 0;
}

In your case you would declare the function in a header file and define it in a cpp file.在您的情况下,您将在头文件中声明该函数并在 cpp 文件中定义它。 Don't forget to compile the cpp file and link it in.不要忘记编译 cpp 文件并链接它。

Check for example What is the difference between a definition and a declaration?检查例如定义和声明之间有什么区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM