在'CompaniesMap.h'中:
class CompaniesMap
{
public:
...
// The companies map
map<string, CompanyP> companies;
};
typedef map<string, CompanyP>::iterator map_it;
在'CompaniesMap.cpp'中:
string* CompaniesMap::displayCompaniesList() const
{
string* compList = new string[companies.size() + 1]; // We add 1 so we can start with the [1] index for simplicity
// Check if 'companies' is empty
if (companies.empty())
{
cout << "No companies in the database." << endl;
return nullptr;
}
for (map_it it = companies.begin(), int i = 1; it != companies.end(); ++it, i++)
{
cout << " " << i << ") " << it->first << endl;
compList[i] = it->first;
}
}
Visual Studio在companies.begin()
下显示一条红线,并显示以下错误消息:
我已尝试将代码从map_it it =
更改为map<string, CompanyP>::iterator
但我仍然收到此错误
我在main.cpp
中使用相同的代码,但决定将其移至单独的类,我包含相同的相关标题,但仍然看到此错误。当我尝试构建时,我从这个文件中得到了不同的错误:
1>d:\asaf\c\vs\hw5\hw5\hw5\companiesmap.cpp(66): error C2062: type 'int' unexpected
1>d:\asaf\c\vs\hw5\hw5\hw5\companiesmap.cpp(66): error C2065: 'i' : undeclared identifier
1>d:\asaf\c\vs\hw5\hw5\hw5\companiesmap.cpp(66): error C2143: syntax error : missing ';' before ')'
1>d:\asaf\c\vs\hw5\hw5\hw5\companiesmap.cpp(67): error C2143: syntax error : missing ';' before '{'
1>d:\asaf\c\vs\hw5\hw5\hw5\companiesmap.cpp(68): error C2065: 'i' : undeclared identifier
1>d:\asaf\c\vs\hw5\hw5\hw5\companiesmap.cpp(69): error C2065: 'i' : undeclared identifier
答案 0 :(得分:2)
displayCompaniesList
是const
函数,这意味着您无法对类中定义的变量进行任何更改。
companies
将是const std::map<std::string, CompanyP>
,而不是std::map<std::string, CompanyP>
,因此您必须相应地更改迭代器:
std::map<std::string, CompanyP>::const_iterator it = companies.begin();
//Or even better if you use C++11
auto it = companies.begin();