C++ 用向量实现堆栈的问题

C++ 用向量实现堆栈的问题,c++,visual-c++,c++11,C++,Visual C++,C++11,在课堂上说: class X { int _top; vector<int> _stack; public: X() { } // SOME CONSTRUCTOR }; 但这些都不起作用: 一, 二, 请解释。工作表单使用向量的构造函数-这在初始值设定项列表中是允许的 第一个非工作状态看起来像是您尝试显式调用vectors构造函数-这是不允许的,vectors已经被构造。初始值设定项列表允许您使用显式构造函数调用替换超类和成员变量的默认构造 第三个不

在课堂上说:

class X
{
     int _top;
     vector<int> _stack;
public:
     X() { } // SOME CONSTRUCTOR
};
但这些都不起作用:

一,

二,


请解释。

工作表单使用向量的构造函数-这在初始值设定项列表中是允许的

第一个非工作状态看起来像是您尝试显式调用vectors构造函数-这是不允许的,vectors已经被构造。初始值设定项列表允许您使用显式构造函数调用替换超类和成员变量的默认构造


第三个不起作用,因为vector没有实现接受int的赋值运算符。它可以修改为_stack。resizecapacity

第一个有效,因为您正在初始化初始化列表中的_stack,而第二个表单不使用初始化列表

阅读此代码中的注释,了解什么是初始化列表

struct sample
{
    int a,b,c; 
    vector<int> _stack;
    sample(int capacity) : _stack(capacity), a(1), b(10), c(100) {} 
           // ^^^^^^^^^^^^^^^^^^^^^ this is called initialization list  

    sample(int capacity, int x) 
    {
       _stack(capacity); //wrong!

       a = b = c = x; // this is called assignment
       //here, inside the constructor body you cannot 
       //initialize member variables, because members has been 
       //constructed and initialized already by the time executions comes here!
    } 
};
基本上,语法_stackcapacity调用构造函数。构造函数只能在构造对象时调用。一旦构建了对象,就不能调用构造函数。在第二种形式中,您试图通过在构造函数体中写入_stackcapacity来调用构造函数,但到那时_stack已经构建好了,这就是代码无法工作的原因

有关初始化列表的详细信息,请阅读此常见问题解答:


在第一种形式中,您调用的是构造函数,但不是第二种和第三种

在1中,您调用的是vector::operator int,它不是为vector定义的

在2中,你被分配一个int到向量,这个向量也没有定义

另外,请记住std::vectorsize\u t n构造函数不仅仅保留内存,而是用n个零填充向量。如果需要在不向向量添加任何值的情况下设置容量,请调用vector::reservesize\u t

如果这不是通过vector实现堆栈本身的目标,那么标准库中已经有了std::stack容器适配器

stack<int> myStack;


这个表单可以工作,因为它调用类成员的构造函数

X( int capacity )
    : _stack( capacity ), //calls vector(int) constructor
    _top( 0 ) // calls int(int) constuctor
{ }
1.这不起作用,因为一旦进入构造函数体,就应该使用其他语法调用构造函数

X( int capacity )
{ 
    _stack( capacity ); //this is not a constuctor call. But this is vector operator()(int) call. And vector does not have this operator defined.
    //the proper constructor call in this place would be _stack = vector<int>( capacity );
    _top=0;
}

如何理解这个叫做初始化列表的东西?你可能指的是不编译?
stack<int> myStack;
stack<int, vector<int> > myVectorBasedStack;
X( int capacity )
    : _stack( capacity ), //calls vector(int) constructor
    _top( 0 ) // calls int(int) constuctor
{ }
X( int capacity )
{ 
    _stack( capacity ); //this is not a constuctor call. But this is vector operator()(int) call. And vector does not have this operator defined.
    //the proper constructor call in this place would be _stack = vector<int>( capacity );
    _top=0;
}
vector<int> _stack( capacity );
vector<int> _stack = vector<int>( capacity );
X( int capacity ){ _stack = capacity;  _top=0; }