1

我在 Mac 上学习了 c++,最近转移到了 Windows 7。我下载了 windows v7.1 sdk 并运行了安装程序。它是 .net 4 依赖版本的 sdk,我安装了 .net 4。

我使用命令行是因为我更喜欢使用它,我在 mac 上使用 gcc 编译器做到了这一点,考虑到我对编程很陌生,所以我很擅长它。

我一直在使用 v7.1 sdk 开发人员命令提示符,因为它使用 SetEnv 批处理文件设置环境变量。

编译器显然是微软的 cl.exe 编译器。

我运行了典型且非常简单的 hello world 程序,最后包括一个 getchar() 让我真正看到该程序,这是由于 mac 不需要的新东西。getchar 工作正常,程序编译并运行良好。

当我尝试编译我在 mac 上编写的一些源代码时,问题出现了。顺便说一句,它在mac上编译得很好。它开始抛出一些非常奇怪的错误,例如告诉我逻辑“与”运算符是未定义的标识符。现在我在这里可能是个愚蠢的人,但据我了解,and 运算符不是标识符,而是运算符。

所以我决定通过编写一个非常简单的程序来缩小问题的范围,该程序使用一个 if 语句和一个 else 语句以及“and”运算符,看看会发生什么。下面是我尝试编译的代码:

//hello, this is a test

#include <iostream>

int main()

{

    char end;
    int a = 0, b = 0;

    std::cout << "If the variable a is larger than 10 and variable b is less than a, then b will be subtracted from a, else they are added.\n";
    std::cout << "Enter a number for variable a\n";
    std::cin >> a;
    std::cout << "Now enter a number for variable b\n";
    std::cin >> b;

    if (a>10 and b<a) a - b;
    else a+b;
    std::cout << "The value of a is: " <<a;

    std::cout << "Press any key to exit";
    end = getchar();
    return 0;
}

这是我用来编译程序的命令

cl /EHsc main.cpp

最后但同样重要的是,这个程序引发的错误列表,为什么这些错误在这里我不确定。这对我来说没有任何意义。

主文件

error C2146: syntax error : missing ')' before identifier 'and'

error C2065: 'and' : undeclared identifier

error C2146: syntax error : missing ';' before identifier 'b'

error C2059: syntax error : ')'

error C2146: syntax error : missing ';' before identifier 'a'

warning C4552: '<' : operator has no effect; expected operator with side-effect

warning C4552: '-' : operator has no effect; expected operator with side-effect

error C2181: illegal else without matching if

warning C4552: '+' : operator has no effect; expected operator with side-effect

这些错误中的每一个都很奇怪。我以前从未遇到过,也从未问过问题,因为我总是能够不问就找到答案,但在这个问题上,我真的很难过。

4

2 回答 2

7

这是 Microsoft Visual C++ 编译器中的一个错误(一项功能) - 它不支持关键字and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq. 您应该使用更常用的运算符,例如&&而不是and||而不是or等。等价表:

+--------+-------+
| and    |  &&   |
| and_eq |  &=   |
| bitand |  &    |
| bitor  |  |    |
| compl  |  ~    |
| not    |  !    |
| not_eq |  !=   |
| or     |  ||   |
| or_eq  |  |=   |
| xor    |  ^    |
| xor_eq |  ^=   |
+--------+-------+

与 C++ 不同,C 不提供这些关键字,而是提供<iso646.h>带有一组宏的标头,这些宏的名称可扩展为这些逻辑运算符。这样做是为了为过去在键盘上不需要字符的机器提供支持。

因为 C++ 尽量避免使用宏,所以 C++ 头文件等效<ciso646>项没有定义任何宏,而是作为内置关键字提供的。

正如这里所指出的,较新版本的 MSVC 可能会为此添加一些支持,但您应该知道那些“替代运算符”很少使用。我建议你坚持使用原始的 C 语法。

于 2017-11-25T19:56:17.060 回答
2

这些替代运算符在标头中定义<iso646.h>为 Visual C++ 实现中的宏。它们与其他语言一起内置于 C++ 语言中。要么包括这个标题:

#include <iso646.h>

/permisive-在使用 Visual C++ 编译器时使用编译器开关进行编译。 许可编译器开关 使用 GCC 编译时不需要包含上述头文件。GCC 实现似乎尊重替代运算符表示参考,其中指出:

包含文件中的 C 编程语言中将相同的词定义<iso646.h>为宏。因为在 C++ 中这些是内置在语言中的,所以 C++ 版本的<iso646.h>以及<ciso646>没有定义任何东西。

Coliru 上的实时示例

于 2017-11-25T19:55:38.940 回答