我是VC的初学者,问个简单问题。在VC6中建立一个Win32 Console Application,然后想做一个堆栈类,源码如下:
#include "stdafx.h"
#include "iostream.h"
class IStack
{
public:
IStack ():_top(0)
{
}
void Push (int i)
{
_arr[_top] = i;
_top++;
} int Pop ()
{
_top--;
return _arr[_top];
}
private:
int _arr[16];
int _top;
};int main(int argc, char* argv[])
{
IStack stack;
stack.Push(1);
stack.Push(2);
cout << stack.Pop() << endl;
cout << stack.Pop() << endl;
return 0;
}
这样是没有问题的。可是,如果我将类的定义放到一个头文件之后,就有问题了,根本就没有将数压入堆栈,因为得到的结果是-858993460。源码如下:stack.h
class IStack
{
public:
IStack () :_top (0) {}
void Push (int i);
int Pop ();
private:
int _arr [16];
int _top;
};
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Section1.cpp#include "stdafx.h"
#include "stack.h"
#include "iostream.h"
void IStack::Push ( int i )
{
_arr [ _top ] = i;
_top++;
}int IStack::Pop ()
{ _top++;
return _arr [ _top ];
}int main(int argc, char* argv[])
{
IStack stack;
stack.Push( 1 );
stack.Push( 2 ); cout << "Popped " << stack.Pop() << endl;
cout << "Popped " << stack.Pop() << endl;
return 0;
}
#include "stdafx.h"
#include "iostream.h"
class IStack
{
public:
IStack ():_top(0)
{
}
void Push (int i)
{
_arr[_top] = i;
_top++;
} int Pop ()
{
_top--;
return _arr[_top];
}
private:
int _arr[16];
int _top;
};int main(int argc, char* argv[])
{
IStack stack;
stack.Push(1);
stack.Push(2);
cout << stack.Pop() << endl;
cout << stack.Pop() << endl;
return 0;
}
这样是没有问题的。可是,如果我将类的定义放到一个头文件之后,就有问题了,根本就没有将数压入堆栈,因为得到的结果是-858993460。源码如下:stack.h
class IStack
{
public:
IStack () :_top (0) {}
void Push (int i);
int Pop ();
private:
int _arr [16];
int _top;
};
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Section1.cpp#include "stdafx.h"
#include "stack.h"
#include "iostream.h"
void IStack::Push ( int i )
{
_arr [ _top ] = i;
_top++;
}int IStack::Pop ()
{ _top++;
return _arr [ _top ];
}int main(int argc, char* argv[])
{
IStack stack;
stack.Push( 1 );
stack.Push( 2 ); cout << "Popped " << stack.Pop() << endl;
cout << "Popped " << stack.Pop() << endl;
return 0;
}
Section1.cpp#include "stdafx.h"
#include "stack.h"
#include "iostream.h"
void IStack::Push ( int i )
{
_arr [ _top ] = i;
_top++;
}int IStack::Pop ()
{ _top++; ----- 应该改为: _top --;
return _arr [ _top ];
}int main(int argc, char* argv[])
{
IStack stack;
stack.Push( 1 );
stack.Push( 2 ); cout << "Popped " << stack.Pop() << endl;
cout << "Popped " << stack.Pop() << endl;
return 0;
}
来丢脸了,谢谢兄弟了。看书都看晕了。FT~~~~
int IStack::Pop ()
{ _top++;
return _arr [ _top ];
}
应该是:
int IStack::Pop ()
{
return _arr [ _top ];
_top--;
}
{
return _arr [ _top ];
_top--;
}
?????????????????????????????????????????????????????????????????????????
int IStack::Pop ()
{
return _arr [ _top-- ];
}