我是 C++ 的新手,正在编写一个简单的程序来测试字符串的使用情况。我已经定义了一个单独的函数,它返回一个字符串并想在 main 方法中调用它。相同的代码在 main 方法中工作,但我需要将其定义为一个单独的函数。
我的代码如下:
7 #include <cstdlib>
8 #include <iostream>
9 #include <string>
10
11 using namespace std;
12
13 // function declaration
14 string hi();
15
16 int main(int argc, char** argv) {
17 // call method
18 string hi;
19 hi = hi();
20 cout << hi << endl;
21 }
22
23 string hi() {
24 //simple string function
25 return "Hello World";
26 }
下面是当我尝试使用 g++ 编译时返回到控制台的错误:
test.cpp: In function ‘int main(int, char**)’:
test.cpp:19:13: error: no match for call to ‘(std::__cxx11::string {aka std::__cxx11::basic_string<char>}) ()’
hi = hi();
^
最佳答案
你用你的变量名来隐藏你的函数声明。你可以做 2 件事中的 1 件事:
关于c++ - 在 main 方法中调用返回字符串的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39216352/