函数返回引用不与window.h一起使用

con*_*ist 2 c++ reference function visual-studio

1: #include <windows.h>

2: int& max(int& a, int& b)
3: {
4:   return a > b ? a : b;
5: }

6: int main()
7: {
8:   return 0;
9: }
Run Code Online (Sandbox Code Playgroud)

Visual Studio 2008速成版大喊:

1> e:...\main.cpp(2):错误C2062:输入'int'意外

1> e:...\main.cpp(2):错误C2062:输入'int'意外

1> e:...\main.cpp(2):错误C2059:语法错误:')'

1> e:...\main.cpp(3):错误C2143:语法错误:缺少';' 在'{'之前

1> e:...\main.cpp(3):错误C2447:'{':缺少函数头(旧式正式列表?)

如果我用stdio.h或iostream替换windows.h似乎有效(或者如果我删除它)

为什么是这样?

use*_*353 5

#include <windows.h>

#undef min
#undef max

int & max(int& a, int& b)
{
    return a > b ? a : b;
}
int main()
{
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

<windows.h>定义宏maxmin干扰你的宏.

其他方法

  • 还有另一种(imho首选)方式:在包含windows.h之前定义NOMINMAX(或使用编译器标志来添加定义).这将阻止windows.h定义两个宏. (2认同)