64,282
社区成员
发帖
与我相关
我的任务
分享
#ifndef _HANDLE_H
#define _HANDLE_H
class Handle{
struct StackOfInt;
StackOfInt* smile;
public:
void initialize();
void cleanup();
void push(int elem);
int fetch();
int pop();
int count();
};
#endif//_HANDLE_H
#include<iostream>
#include<vector>
#include "handle.h"
using namespace std;
struct Handle::StackOfInt{
vector<int> top;
};
void Handle::initialize()
{
StackOfInt* smile = new StackOfInt;
smile->top.reserve(100);
cout << smile->top.capacity() << endl;
}
void Handle::cleanup()
{
delete smile;
}
void Handle::push(int elem)
{
cout << "before push\n";
smile->top.push_back(elem);
cout << "after push\n";
}
int Handle::fetch()
{
return smile->top.back();
}
int Handle::pop()
{
int n = smile->top.back();
smile->top.pop_back();
return n;
}
int Handle::count()
{
return smile->top.size();
}
#include<iostream>
#include "handle.h"
using namespace std;
int main()
{
Handle h;
h.initialize();
for (int i = 0; i < 10; i++)
{
h.push(i);
cout << "last element is " << h.fetch() << endl;
}
for (int i = 0; i < 10; i++)
{
h.pop();
}
return 0;
}
void Handle::initialize()
中的smile是局部变量,Handle中的smile未被赋值。void Handle::initialize()
{
/* StackOfInt* */smile = new StackOfInt;
smile->top.reserve(100);
cout << smile->top.capacity() << endl;
}
StackOfInt* smile = new StackOfInt;
把前面的StackOfInt* 去掉
struct StackOfInt;
这个语句是定义了类内部的一个类吧?那么在定义类的时候,不是应该把它的所有成员都列出来吗?比如说这样:
struct StackOfInt{
vector<int> top;
};