【问题标题】:Main method is different to those in tutorials主要方法与教程中的方法不同
【发布时间】:2014-01-14 04:55:08
【问题描述】:

所以我从 c++ 开始(我试图用新语言拓宽我的思维),但我遇到了一个小问题,这比我猜想的更让我困惑......

使用 Visual Studio Express 2012,我在 C++ 中创建了一个控制台 win32 应用程序,这是我的主要方法声明:

// TestApp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

但是,由于我对 c++ 一无所知,所以我在网上搜索了一些 tuts,所有这些都以不同的方式设置了 declerations

#include <iostream>

using namespace std;

int main()
{
  cout<<"HEY, you, I'm alive! Oh, and Hello World!\n";
  cin.get();
}

// my first program in C++
#include <iostream>

int main()
{
  std::cout << "Hello World!";
}

我尝试输入“std::cout”,但它不接受, 有人可以澄清差异的原因和意义吗?

【问题讨论】:

标签: c++ visual-c++ main


【解决方案1】:

C++ 程序可能有两个开端之一:

        int main(int argc, char *argv[])

        int wmain(int argc, wchar_t *argv[])

其中第一个将其参数 (argv) 作为 ANSI 字符,而第二个获得“宽”字符 - 通常为 UTF-16 或 UTF-32,具体取决于平台。

Microsoft 定义了一个框架,允许您编写可以使用 ANSI 或宽字符进行编译的代码。

        int _tmain(int argc, TCHAR *argv[])

在幕后,他们有这样的事情:

        #if defined UNICODE
            #define _tmain wmain
            #define TCHAR wchar_t
        #else
            #define _tmain main
            #define TCHAR char
        #endif

它们还具有辅助函数,例如 _tprintf()_tcscpy()

注意:正如其他人指出的那样, argc 和 argv 参数是可选的,所以你也可以有

        int main()

        int wmain()

和(对于 Microsoft 和兼容的编译器)

        int _tmain()

另请注意,虽然_tmain() 不是严格可移植的,但如果您想移植到其他平台,您可以轻松创建自己的 #define 宏。

【讨论】:

  • 没有。 wmain 不是合法的 C++ - 它是 Microsoft 扩展,与 _tmain 相同。
  • 我的立场是正确的。我认为 wmain() 已添加到标准中,但快速搜索并没有显示任何支持。很明显,我最近做了太多的 Windows 编程。
【解决方案2】:
int _tmain(int argc, _TCHAR* argv[])

是(至少我是这么认为的)一个仅限 Windows 的库和编译器,具体取决于声明主函数的方式。

这样声明 main 绝对没有错:

int main(int argc, char const *argv[])
{
    //do something
    return 0;
}

或者像这样:

int main()
{
    //do something
    return 0;
}

这绝对是正确的 C++,您可以普遍使用它。

【讨论】:

    【解决方案3】:

    main方法可以带参数也可以不带参数定义。这完全取决于您使用应用程序的目的。

    看看这个:https://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fmainf.htm

    对于您的程序,您还需要有一个返回值

    // my first program in C++
    #include <iostream>
    
    int main()
    {
      std::cout << "Hello World!";
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      • 2014-11-22
      • 2014-08-23
      • 2017-12-05
      • 1970-01-01
      • 2014-06-18
      相关资源
      最近更新 更多