什么是C ++中的“预期的不合格ID”错误?

时间:2018-09-07 08:05:38

标签: c++ bitset

我正在尝试学习stl:bitmap,但是出现以下错误: 标头已添加 -位 -字符串

我已经在其他SO帖子中搜索了此错误,但它们与位集无关。

我的代码

int main(){
    bitset<size> bs;
    bitset<10> bs2(45);
    bitset<13> bs3("1100101");

    cout << "bs: " << bs << endl;
    cout << "bs1: " << bs2 << endl;
    cout << "bs2: " << bs3 << endl;
    cout << endl;

    cout << "bs has " << bs.count() << " set bits" << endl;

    cout << bs.size() << endl;
    cout << bs2.size() << endl;
    cout << bs3.size() << endl;
}

我的错误:最近3个cout语句中的错误。

$ g++ test.cpp 
test.cpp:28:16: error: expected unqualified-id
    cout << bs.size() << endl;
               ^
test.cpp:6:14: note: expanded from macro 'size'
#define size 16
             ^
test.cpp:29:17: error: expected unqualified-id
    cout << bs2.size() << endl;
                ^
test.cpp:6:14: note: expanded from macro 'size'
#define size 16
             ^
test.cpp:30:17: error: expected unqualified-id
    cout << bs3.size() << endl;
                ^
test.cpp:6:14: note: expanded from macro 'size'
#define size 16
             ^
3 errors generated.
$ 

3 个答案:

答案 0 :(得分:2)

从程序中删除#define size 16。我想您已经在程序顶部编写了这一行。

您定义的

size宏与size()成员函数冲突。使用const变量而不是宏。您应该使用const int size=16;

答案 1 :(得分:1)

您似乎在test.cpp第6行中定义了一个宏,该宏替换了您尝试调用函数size的字符串。

您的行实际上是在说:

cout << bs.16() << endl;
cout << bs2.16() << endl;
cout << bs3.16() << endl;

如果要使用宏,则最好使它们尽可能具有描述性,并使用ALL_UPPER_CASE来避免此类问题。

例如 #define BITSET_DEFAULT_SIZE 16

编译器给出的错误描述非常具有描述性,并让您知道宏是导致此问题的原因:

test.cpp:28:16: error: expected unqualified-id
    cout << bs.size() << endl; <- this is telling you the starting position of the error
               ^
test.cpp:6:14: note: expanded from macro 'size'
    #define size 16 <- this is telling you a macro is involved, and giving its value

此外,由于using namespace std包含许多泛型命名函数,因此在程序中使用std也不是一个好习惯。例如,如果创建一个名为size的函数,则会突然覆盖std::size

Here is a good post pointing out why this is a bad idea

答案 2 :(得分:0)

使用

#undef size 

紧随行后

bitset<size> bs;

这将隐藏您的宏,其余代码现在应编译。

注意:这不是永久性修复。但是,如果宏位于许多文件中包含的头文件中,则将提供临时修复。但是建议在宏中使用C ++中的const。

相关问题