如何解决`没有可行的重载operator []类型&#39; std :: map <audiotypes,const =“”char =“”* =“”>`?

时间:2016-03-07 18:27:56

标签: c++ c++11

所以为了我的目的,我遵循了这个SO answer,我真的不知道如何解决这个错误。当我尝试访问audioType[wav]audioType[mp3]时,会出现以下错误消息。查找互联网对我没有帮助。

error: no viable overloaded operator[] for type 'const std::map<AudioTypes, const char *>

note: candidate function not viable: 'this' argument has type 'const std::map<AudioTypes, const char *>', but method is not marked const mapped_type& operator[](const key_type& __k);

// WAVFile.h
class WAVFile {
    // ...
    private:
        enum AudioTypes: int;
        static std::map<AudioTypes, const char*> audioType;
    // ...
}

// WAVFile.cpp
enum AudioTypes: int {
    wav,
    mp3
};

static map<AudioTypes, const char*> audioType = {
    {wav, "wav"},
    {mp3, "mp3"}
};

bool WAVFile::exportAudio(const char* filename, const char* filetype) {
    // temporary test code    
    cout << audioType[wav] << endl;
    return true;
}

// main.cpp
int main() {
    file.exportAudio("export_i ran.wav","wav") ? cout << "Exported\n" : cout << "Failed\n";

    return 0;
}

2 个答案:

答案 0 :(得分:4)

正如已经指出的那样,该错误的原因是 - 正如错误消息所解释的那样 - operator[]的{​​{1}}不是std::map合格的成员函数。 (我对此感到有些惊讶,我认为有一个const重载)

可能的解决方法是使用具有此const限定重载的member function at,因此应使用const限定const s。

另请注意,在您显示的代码中可能存在问题:

std::map

class WAVFile {
        static std::map<AudioTypes, const char*> audioType;
}

不是同一个变量。您应该在定义之前添加类范围并删除static map<AudioTypes, const char*> audioType = { {wav, "wav"}, {mp3, "mp3"} };

static

此外,您应该将map<AudioTypes, const char*> WAVFile::audioType = { {wav, "wav"}, {mp3, "mp3"} }; 的定义移至标题,或者可以提供forward declaration

答案 1 :(得分:1)

修复了一些问题,特别是WAVFile::audioType之前缺少的AudioTypes以及audioType定义之前的静态问题,此代码构建:

#include <map>
#include <iostream>

using namespace std;

class WAVFile {
    public:
        bool exportAudio(const char* filename, const char* filetype);

    private:
        enum AudioTypes: int;
        static std::map<AudioTypes, const char*> audioType;
};

enum WAVFile::AudioTypes: int {
    wav,
    mp3
};

map<WAVFile::AudioTypes, const char*> WAVFile::audioType = {
    {wav, "wav"},
    {mp3, "mp3"}
};

bool WAVFile::exportAudio(const char* filename, const char* filetype) {
    cout << audioType[wav] << endl;
    return true;
}

int main() {
    WAVFile file;

    file.exportAudio("export_i ran.wav","wav") ? cout << "Exported\n" : cout << "Failed\n";

    return 0;
}