c++ - 没有合适的用户定义转换

标签 c++ compiler-errors iterator syntax-error

在“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() 下显示一条红线出现以下错误消息: enter image description here

我尝试更改 map_it it = 中的代码至 map<string, CompanyP>::iterator但是我仍然得到这个错误

我在 main.cpp 中有相同的代码但决定将其移至单独的类,我包含相同的相关 header ,但仍然看到此错误。当我尝试构建时,我从这个文件中得到了不同的错误:

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

最佳答案

displayCompaniesListconst函数,这意味着您不能对类中定义的变量进行任何更改。

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();

关于c++ - 没有合适的用户定义转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37765750/

相关文章:

c++ - 为什么从 char 数组创建的 ostream std::string 上的段错误

java - GLSL着色器-片段着色器无法编译

java - 在 Android 的 Java 中将此字符串分解为键/值字符串的最简单方法是什么?

c++ - 如何使用以下模板为 map 声明迭代器 - std::map<std::string, T> my_map?

java - 如何从多个迭代器创建并行拆分器?

c++ - 如何使用 gzip 压缩压缩包?

C++ 删除 static_cast<void*> (指针)行为

c++ - IDE 中的更多内容(eclipse cdt)

c++ - 二进制表达式('std::__1::ostream'(aka 'basic_ostream<char>'和 'void')的无效操作数

swift - 必须指定 Swift 协议(protocol)中的初始化程序。为什么呢?