有必要把一个编译好的实际结构放在实现文件中,而不是让其暴露在头文件中。
StackOfInt.h
// StackOfInt classes
#ifndef StackOfInt_H
#defint StackOfInt_H
class StackOfInt
{
struct Cheshire;
Cheshire* smile;
public:
void initialize();
void add(int);
void print();
void cleanup();
};
#endif
StackOfInt.cpp
#include "StackOfInt.h"
// Defint StackOfInt's implementation:
struct StackOfInt::Cheshire
{
vector<int> v;
};
void StackOfInt::initialize()
{
smile = new Cheshire;
}
void StackOfInt::add(int x)
{
smile->v.push_back(x);
}
void StackOfInt::print()
{
for (int i=0; i<v.size(); i++)
cout<<i<<": "<<v[i]<<endl;
}
void StackOfInt::cleanup()
{
delete smile;
}
UseStackOfInt.cpp
#include "StackOfInt.h"
int main()
{
StackOfInt StackImp;
StrackImp.initialize();
for (int i=1; i<5; i++)
StackImp.add(i*i);
StackImp.print();
StackImp.cleanup();
return 0;
}