结局我一人 发表于 2015-4-14 10:06

vector调用push_back为什么会失败?初始化了也不行

头文件handle.h
#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

类class的函数定义
#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();
}

主函数 main.cpp
#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;
}



超级管理员 发表于 2015-4-14 21:29

是代码里缺东西了吗?

页: [1]
查看完整版本: vector调用push_back为什么会失败?初始化了也不行