2011-03-16 67 views
0

在Stack类说:问题在实施使用Vector

class X 
{ 
    int _top; 
    vector<int> _stack; 
public: 
    X() { } // SOME CONSTRUCTOR 
}; 

为什么会出现这种形式的构造原理:

X(int capacity) 
    : _stack(capacity), _top(0) { } 

但这些不工作:

1.

X(int capacity) 
{ _stack(capacity); _top=0; } 

2.

X(int capacity) 
    {_stack = capacity; _top=0;} 

请说明。

+0

由“不工作”你可能是指“不编译”? – davka 2011-03-16 10:57:44

回答

4

第一个工作,因为您正在初始化列表中初始化_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! 
    } 
}; 

基本上,语法_stack(capacity)调用构造函数。构造函数只能在构造对象时调用。一旦构造对象,就不能调用构造函数。在第二种形式中,您试图通过在构造函数体中编写_stack(capacity)来调用构造函数,但到那时_stack已经被构建,这就是为什么您的代码不起作用!

有关初始化列表细节,请阅读此FAQ:

[10.6] Should my constructors use "initialization lists" or "assignment"?

+1

如何理解这个叫做“初始化列表”的东西? – Sadique 2011-03-16 10:44:36

+0

@Acme:再次看到我的答案。我更新了它! – Nawaz 2011-03-16 10:47:44

+1

谢谢纳瓦兹.... – Sadique 2011-03-16 11:15:38

0

工作表单使用向量的构造函数 - 这是在初始化程序列表中允许的。

第一个非工作看起来像你试图显式调用矢量构造函数 - 这是不允许的,矢量已经被构造。初始化程序列表允许用显式构造函数调用来替换超类和成员变量的默认构造。

第三个不起作用becase向量没有实现一个赋值运算符。它可以修改为_stack.resize(capacity)

2

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

1您正在呼叫vector<T>::operator()(int),这是没有为vector<T>定义。

2中,您被分配了一个intvector<T>,这也未定义。

另请注意,std::vector<int>(size_t n)构造函数不只是保留内存,而是用n零填充向量。如果您需要设置容量而不实际向矢量添加任何值,请致电vector<T>::reserve(size_t)

如果这不是通过vector实现堆栈的目标本身,则可以在标准库中使用std::stack容器适配器。

stack<int> myStack; 

或者

stack<int, vector<int> > myVectorBasedStack; 
1

这种形式的作品,因为它调用的类成员的构造函数。

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为载体,并在同一时间初始化可以这样写:

vector<int> _stack(capacity); 

但是,这只是一个简称:

vector<int> _stack = vector<int>(capacity); 

2,本是错误的,显然是因为你不能只是分配整数到向量

X(int capacity){ _stack = capacity; _top=0; }