警告 "C++ requires a type specifier for all declaration" 图

Warning "C++ requires a type specifier for all declaration" map

我 运行 这段代码在 xcode 中。为什么我的编译器一直抱怨映射分配

#include <iostream>
#include <map>
#include <deque>
using namespace std;

map<int,deque<int>> bucket;
deque<int> A{3,2,1};
deque<int> B;
deque<int> C;


bucket[1] = A;//Warning "C++ requires a type specifier for all declaration
bucket[2] = B;//Warning "C++ requires a type specifier for all declaration
bucket[3] = C;//Warning "C++ requires a type specifier for all declaration

int main() {

    for (auto it:bucket)
    {
        cout << it.first << "::";
        for (auto di = it.second.begin(); di != it.second.end(); di++)
        {
            cout << "=>" << *di;
        }
        cout << endl;
    }

    return 0;
}

好像我在 main 中做了同样的事情,它的工作非常完美

#include <iostream>
#include <map>
#include <deque>
using namespace std;

map<int,deque<int>> bucket;
deque<int> A{3,2,1};
deque<int> B;
deque<int> C;  

int main() {

    bucket[1] = A;
    bucket[2] = B;
    bucket[3] = C;

    for (auto it:bucket)
    {
        cout << it.first << "::";
        for (auto di = it.second.begin(); di != it.second.end(); di++)
        {
            cout << "=>" << *di;
        }
        cout << endl;
    }

    return 0;
}

输出

1::=>3=>2=>1
2::
3::
Program ended with exit code: 0

这是我遗漏的东西吗?无法理解这种行为。 任何建议、帮助或文档。我调查了类似的问题,但没有得到令人满意的答案

是因为三行...

bucket[1] = A;//Warning "C++ requires a type specifier for all declaration
bucket[2] = B;//Warning "C++ requires a type specifier for all declaration
bucket[3] = C;//Warning "C++ requires a type specifier for all declaration

是语句。您不能在 C 中的函数外部执行语句(C 不是 Python)。如果将这三行代码移到 main() 中,那么它应该可以正常工作。

编译器识别这段代码

bucket[1] = A;
bucket[2] = B;
bucket[3] = C;

as a declarations which shall have type specified, because you cannot run executable code (which invoking the assignment operator is) 在函数之外(或在声明变量时作为初始化程序)。 在以下情况下:

map<int,deque<int>> bucket;
deque<int> A{3,2,1};
deque<int> B;
deque<int> C;  

map<int,deque<int>>deque<int> 是类型说明符。

你不能在全局范围内做这样的事情

int i;
i = 100;

因为在 C++11 中,您可以在声明时初始化值

int i = 100;

或在函数内设置值

int main() {
 i = 100;
}

STL 初始化也是如此,这就是您遇到问题的原因

在函数范围之外初始化变量的方法是

std::deque<int> A{3,2,1};
std::deque<int> B;
std::deque<int> C; 
std::map<int, std::deque<int>> bucket {{1, A}, {2 , B}, {3, C}};