Skip to content

Instantly share code, notes, and snippets.

@nus
Created November 26, 2010 13:54
Show Gist options
  • Save nus/716739 to your computer and use it in GitHub Desktop.
Save nus/716739 to your computer and use it in GitHub Desktop.
learning Pointer Implemetation
//==================file.h===========
#ifndef FILE_H
#define FILE_H
class file
{
public:
file();
file(const file& rhs);
file& operator =(const file&);
~file();
void read(const char *file_name);
void show();
private:
class impl;
impl* pimpl;
};
#endif
//===============end of file.h===========
//==================file.cpp==============
#include "file.h"
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
class file::impl
{
public:
// ファイルの読み込み
void read(const char *file_name)
{
std::ifstream fin(file_name);
std::string line;
while(fin && getline(fin, line))
{
line_data.push_back(line);
}
fin.close();
}
// ファイルの表示
void show()
{
std::vector<std::string>::iterator it;
for(it = line_data.begin(); it != line_data.end(); it++)
{
std::cout << *it << std::endl;
}
}
private:
std::vector<std::string> line_data;
};
file::file()
: pimpl(new file::impl()) {}
file::file(const file &rhs)
: pimpl(new file::impl(*rhs.pimpl)) {}
file::~file()
{
delete pimpl;
}
file&
file::operator =(const file& rhs)
{
impl *tmp = pimpl;
pimpl = new file::impl(*rhs.pimpl);
delete tmp;
return *this;
}
// implの呼び出し
void
file::read(const char *file_name)
{
pimpl->read(file_name);
}
void
file::show()
{
pimpl->show();
}
//===============end of file.cpp==========
//==================main.cpp==============
#include "file.h"
int main()
{
file a;
a.read("main.cpp");
a.show();
}
//==============end of main.cpp===========
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment