c++ - 在 main 方法中调用返回字符串的函数

标签 c++ linux

我是 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 件事:

  1. 重命名函数或变量。 (example)
  2. 在调用中限定名称,这将涉及像这样调用函数的 namespace (即全局 namespace ):::hi()(example)

关于c++ - 在 main 方法中调用返回字符串的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39216352/

相关文章:

c++ - 不能为我的数组大小使用变量,但变量被声明为 const int

c++ - 使用定义相互依赖

c++ - 如果我将 `shared_ptr<T>&` 分配给它的另一个引用会发生什么

在Linux终端中编译C代码

linux - 如何在宕机时使用 Systemd 重启服务?

c++ - SDL2 : Generate fully transparent texture

c++ - 如何对一个元素使用 vector<T>::reverse_iterator

linux - 如何在 linux 中使用 tomcat(clientauth ="true") 构建 ssl

linux - 如何了解 Linux 硬盘上有多少空间?

linux - 在 WordPress 中上传的文件不可见/不可用