c++ - 如何在 C++ 中正确声明函数?
问题描述
我想在 my 中声明一个函数main.cpp
,这样我的main
函数就可以成为文件中的第一个函数。它看起来像这样:
main.cpp
#include <iostream>
#include <string>
using namespace std;
string my_function();
int main () {
my_function();
return 0;
}
string my_function(string message = "") {
string response;
cout << message;
getline(cin,response);
return response;
}
但是,编译时出现错误:
/usr/bin/ld: /tmp/cco8jyj1.o: in function `main':
main.cpp:(.text+0x1f): undefined reference to `my_function[abi:cxx11]()'
collect2: error: ld returned 1 exit status
[Finished in 1.4s with exit code 1]
怎么了?
解决方案
string my_function();
已声明但未定义。
它应该是:
string my_function(string message = "");
...
string my_function(string message) { ... }
推荐阅读
- php - PHP 联系表 GDPR 验证
- c# - 如何将 Serilog 附加到 dotnetcore 日志框架并将日志服务作为开放通用类型注入
- python - 一个比例图中的多线图
- javascript - 如何对具有相同功能的多个元素执行转换
- vim - 如何删除直到(不包括)行上的最后一个字符
- sql - 创建可变报告期:'2019 - 2020'
- python - Python:在数据框中查找特定列值总和为 0 的所有行
- c++ - 在 VS 代码中调试 C++ 时不接受终端中的用户输入
- java - 从 config.file 读取会引发 FileNotFoundException(没有这样的文件或目录)
- java - 我在颤振中从 webview 得到 ERROR:ssl_client_socket_impl.cc(946) 错误