STL中的队列数据结构

3
我正在尝试使用g ++ 4.2.1编译以下代码,并收到以下错误信息。
代码:
#include <iostream>
#include <queue>

using namespace std;

int main (int argc, char * const argv[])
{    
    queue<int> myqueue();
    for(int i = 0; i < 10; i++)
        myqueue.push(i);

    cout << myqueue.size();

    return 0;
}

错误:
main.cpp: In function ‘int main(int, char* const*)’:
main.cpp:10: error: request for member ‘push’ in ‘myqueue’, which is of non-class type ‘std::queue<int, std::deque<int, std::allocator<int> > > ()()’
main.cpp:12: error: request for member ‘size’ in ‘myqueue’, which is of non-class type ‘std::queue<int, std::deque<int, std::allocator<int> > > ()()’

任何想法是为什么?我尝试过在Eclipse、X-Code和终端中运行。
1个回答

10

C++ FAQ Lite § 10.2

使用 List x;List x(); 有什么区别?

有很大的区别!

假设 List 是某个类的名称。函数 f() 声明了一个名为 x 的本地 List 对象:

void f()
{
  List x;     // Local object named x (of class List)
  ...
}

但函数g()声明了一个名为x()的函数,该函数返回一个List

void g()
{
  List x();   // Function named x (that returns a List)
  ...
}
queue<int> myqueue;替换queue<int> myqueue();就可以了。

如果需要进一步的研究,这也有时被称为“最令人烦恼的解析”:http://www.google.com/search?q=most+vexing+parse - Steve Jessop
1
做到了!非常感谢。出于好奇,队列没有构造函数吗?我加括号是因为我必须调用构造函数。或者只有在新建对象时才需要这样做吗? - finiteloop
没有括号的版本会调用无参构造函数。 - Steve Jessop
Foo bar; 构造函数使用 Foo::Foo()Foo bar(a,b,c); 构造函数使用 Foo::Foo(a,b,c)new Foo;new Foo() 都可以构造一个 Foo,但意义略有不同。是的,这很不一致和可怕。这就是 C++ :) 这就是为什么有些人更喜欢写 Foo bar = Foo();Foo bar = Foo(a,b,c); 但我也不太喜欢那样... - ephemient
那么 Foo bar(); 不会调用构造函数 Foo::Foo() 吗?如果它导致编译错误,那就不会。 - finiteloop
不,Foo bar()并没有构造任何东西。相反,它是一个声明:“在这个作用域中,bar是一个不带参数并返回Foo的函数”。当然,仅有声明而没有定义,你不能对bar做任何有用的事情... - ephemient

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接