C ++错误C2664和错误C2679

时间:2014-10-26 19:26:24

标签: c++

所以我的代码如下。我试着看这个东西,但它通常对我的情况没有帮助。任何帮助都是一种祝福。

编译器错误:

error C2679: binary '[' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
    counter[typeOfToken]+=1;

error C2664: 'std::_Tree<_Traits>::count' : cannot convert parameter 1 from 'int' to 'const tokentype &'
    if (counter.count(typeOfToken))

代码:

#include <iostream>
#include <fstream>
#include <map>
#include <cctype>
#include <string>
#include <algorithm>
#include <string.h>
#include <map>

using namespace std;

enum tokentype{ lANGLE=1, rANGLE=2,iD=3, eQ=4, sLASH=5, qSTRING=6, oTHER=7, eND=8, tEXT=9};
tokentype getToken(istream *in, string& lexeme);

int main( int argc, char *argv[] ) {
    istream *br;
    ifstream infile;
    // check args and open the file
    if( argc == 1 )
        br = &cin;
    else if( argc != 2 ) {
        cout<<"THERE IS A FATAL ERROR"<<endl;
        return 1; // print an error msg
    } else {
        infile.open(argv[1]);
        if( infile.is_open() )
            br = &infile;
        else {
            cout << argv[1] << " can't be opened" << endl;
            return 1;
        }
    }

    map <tokentype, int> counter;
    string tokens="";
    int typeOfToken;

    while(true){
        typeOfToken=getToken(br,tokens);
        if (counter.count(typeOfToken))
            counter[typeOfToken]+=1;
        else
            counter[typeOfToken]=1;

        if(typeOfToken==eND)
            break;
    }

    cout<<"total token count: "<<endl;
    if (counter[lANGLE]!=0)
        cout<<"LANGLE: "<<counter[lANGLE]<<endl;
    if (counter[rANGLE]!=0)
        cout<<"RANGLE: "<<counter[rANGLE]<<endl;
    if (counter[tEXT]!=0)
        cout<<"TEXT: "<<counter[tEXT]<<endl;
    if (counter[iD]!=0)
        cout<<"ID: "<<counter[iD]<<endl;
    if (counter[eQ]!=0)
        cout<<"EQ: "<<counter[eQ]<<endl;
    if (counter[sLASH]!=0)
        cout<<"SLASH: "<<counter[sLASH]<<endl;
    if (counter[qSTRING]!=0)
        cout<<"QSTRING: "<<counter[qSTRING]<<endl;
    if (counter[oTHER]!=0)
        cout<<"OTHER: "<<counter[oTHER]<<endl;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

typeOfToken变量的类型不匹配。

它来自getToken,返回类型enum tokentype。它被用作std::map的{​​{1}}的索引。如果您声明enum tokentype

,这两项操作都会很有效

然而,你没有。你把它变成了tokentype typeOfToken;。枚举值隐式转换为整数类型,但反向转换是显式的(需要转换)并且如果您忘记了,则会给出您看到的错误。

当然,修复变量类型以匹配其用法是理想的,在这种情况下你可以。但是如果它的用法是混合的(可能它在某处用于算术),那么你需要一个演员。