1

コンパイラは最も単純なループでさえ処理できません

#include <iostream>
using namespace::std;

int main()
{

    for( int i = 0, char a = 'A'; i <= 26; i++, a++ )

    cout << "OK, lets try. Showing values: i = "
         << i << ", a = " << a << endl;
}

コンパイラはこれを言います:

prog.cpp: In function ‘int main()’:
prog.cpp:7:18: error: expected unqualified-id before ‘char’ 
prog.cpp:7:18: error: expected ‘;’ before ‘char’ 
prog.cpp:7:39: error: expected ‘)’ before ‘;’ token 
prog.cpp:7:41: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive] 
prog.cpp:7:41: note: (if you use ‘-fpermissive’ G++ will accept your code) 
prog.cpp:7:46: error: ‘a’ was not declared in this scope 
prog.cpp:7:50: error: expected ‘;’ before ‘)’ token

はい、ループの前に「i」と「a」を初期化できることはわかっています。それでは、試してみましょう:

#include <iostream>
using namespace::std;

int main()
{
    int i = 0;

    for(i = 0, char a = 'A'; i <= 26; i++, a++ )

    cout << "OK, lets try. Showing values: i = "
         << i << ", a = " << a << endl;
}

コンパイラは次のように述べています。

prog.cpp: In function ‘int main()’:
prog.cpp:8:13: error: expected primary-expression before ‘char’
prog.cpp:8:13: error: expected ‘;’ before ‘char’
prog.cpp:8:41: error: ‘a’ was not declared in this scope

オプション -std=c++11 を使用した場合:

prog.cpp: In function ‘int main()’:
prog.cpp:7:17: error: expected unqualified-id before ‘char’
prog.cpp:7:17: error: expected ‘;’ before ‘char’
prog.cpp:7:38: error: expected ‘)’ before ‘;’ token
prog.cpp:7:40: error: ‘i’ was not declared in this scope
prog.cpp:7:45: error: ‘a’ was not declared in this scope
prog.cpp:7:49: error: expected ‘;’ before ‘)’ token

最後の一つ:

#include <iostream>
using namespace::std;

int main()
{
    int i = 0;
    char a = 'A';

    for(i = 0, a = 'A'; i <= 26; i++, a++ )

    cout << "OK, lets try. Showing values: i = "
         << i << ", a = " << a << endl;
}

正常に動作します。みんな、私は盲目か何かですか?私のアーチとコンパイラのバージョンが必要かもしれません:

uname -a
Linux freelancer 3.2.0-4-686-pae #1 SMP Debian 3.2.63-2+deb7u2 i686 GNU/Linux
g++ --version 
g++ (Debian 4.7.2-5) 4.7.2
4

2 に答える 2

3

同じ宣言で異なる型の項目を宣言することはできません。

これは、ループの内外で当てはまります。あなたは「盲目」ではありません。有効な C++ ではないだけです。

正しいコードは次のとおりです。

#include <iostream>
using namespace::std;

int main()
{
    int i = 0;
    char a = 'A';

    for(; i <= 26; i++, a++ )

        cout << "OK, lets try. Showing values: i = "
            << i << ", a = " << a << endl;
}

宣言を式に置き換えることができるため、作業バージョンも有効ですが、これらの変数はループの開始時にそれらの値を既に保持しているため、冗長です。

于 2020-03-29T17:45:33.720 に答える