c++ - 是否有必要在 main 中声明一个函数?

标签 c++ function

我有一个有点大的程序,它使用类 A 和类的一些函数以及类外的一些全局函数。然后我有该类的多个对象,我希望使用另一个函数同时操作它们。我相信(至少一直被建议)最好在 main 之外声明函数。

但是如果我继续在 main 之外声明,似乎没有合适的方法可以调用我的对象,因为它们的范围仅限于 main,我不想将每个对象作为不同的参数传递,因为那样会很复杂事情了。我相信如果我只是将我的函数放在 main 中,我就不会遇到这些问题。

有没有更优雅的方法来做到这一点?

如果我的问题不清楚,这里是代码大纲:

class A
{
  void A1();
  void A2();
  void A3();
} //class functions that modify class objects

void A4(); //global function(cant call apple elegantly if placed here)

int main() {
  A apple;
  A banana; //class ojects
  A4(); //gotta modify objects apple and banana by calling A1,A2,A3
        // on them depending on the user input
  return 0;
}

此外,在这种情况下,如果最好只在 main 中声明函数,请告诉我。我只想知道如何实现最佳方法而不是任何多余的方法:)

最佳答案

Is it ever necessary to declare a function inside main?

没有。在 C++11 中,lambda 将击败任何其他本地函数。

I want to modify 3 class objects, so that would be just 3 extra arguments everytime i call the function(which is going to be recursive in particular). I dont really see why not i just call it in main . What does it hurt to do that?

您正在创建一个依赖于全局变量或捕获到函数中的变量的函数。你的函数A4()想要修改任何变量,只需将它作为变量传入并多次调用A4()即可操作N次。

void A4(A& a); // A4 can operate on any objects of A type

int main() {
  A apple;
  A banana; //class objects

  A4(apple);  // A4 can operate on any objects of A type
  A4(banana);
  A4(....);   
}

关于c++ - 是否有必要在 main 中声明一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18417472/

相关文章:

c++ - Visual Studio 构建错误 : unresolved external symbol _IID_IWICImagingFactory (MFC static lib)

c++ - 将 uint8 数组传递给函数可减小其大小(C++ 代码)

c++ - 使用 header 时,是否需要插入我的 cpp 文件中使用的每个函数?

c++ - Windows 程序的调用约定最好声明什么?

c++ - C中简单表达式的奇怪输出,为什么?

C++双指针未知转换

c++ - 在运行时创建自定义事件

python - 如何将 lambda 函数读取为字符串?

java - 调用函数而不执行新操作

javascript - 需要回调功能