【问题标题】:How to call a function in main/ experimenting with CPP如何在 main / 试验 CPP 中调用函数
【发布时间】:2020-08-17 10:42:02
【问题描述】:

我目前正在使用 C++ 进行试验,我想知道如何在 main 中调用下面提到的 fun1:

#include <iostream>

int main() {
  std::cout << "Result is: " << fun1(1, 4, 1)();
}

int fun1(int x, int y, int z) {
some stuff
}

我在 fun1 的 main 上遇到错误:

 clang++-7 -pthread -std=c++17 -o main main.cpp
main.cpp:4:33: error: use of undeclared identifier 'fun1'
  std::cout << "Result is: " << fun1(1, 4, 1)();
                                ^
1 error generated.
compiler exit status 1
 

有人可以帮忙解决如何调用 fun1,谢谢。

【问题讨论】:

标签: c++


【解决方案1】:

您需要从调用中删除 the(),它应该是 fun1(1,4,1)。您还需要在 main 之上声明函数,或者将整个函数移到 main 之上,包括实现

#include <iostream>
int fun1(int x, int y, int z);

int main() {
  std::cout << "Result is: " << fun1(1, 4, 1);
}

int fun1(int x, int y, int z) {
some stuff
}

#include <iostream>
int fun1(int x, int y, int z) {
some stuff
}

int main() {
  std::cout << "Result is: " << fun1(1, 4, 1);
}

【讨论】:

    【解决方案2】:

    使用前声明函数。

    并且还像@OmidCompSCI 所说的那样删除额外的()

    #include <iostream>
    
    int fun1(int x, int y, int z); // add this
    
    int main() {
      std::cout << "Result is: " << fun1(1, 4, 1);
    }
    
    int fun1(int x, int y, int z) {
    some stuff
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-25
      • 2016-02-29
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2015-01-30
      相关资源
      最近更新 更多