Hoge.h


#ifndef HOGE_H_
#define HOGE_H_
 
#include <string>
 
class Hoge {
public:
  Hoge();
  Hoge(const Hoge&);
  Hoge& GetReference();
  Hoge GetCopy1();
  Hoge GetCopy2();
  virtual ~Hoge();
private:
  int counter_;
};
 
#endif /* HOGE_H_ */

Hoge.cpp


#include "Hoge.h"
#include <iostream>
 
Hoge::Hoge() : counter_(1) {
  std::cout
    << "Hoge::Hoge(): "
    << this->counter_
    << std::endl;
}
 
Hoge::Hoge(const Hoge& hoge) {
  this->counter_ = hoge.counter_ + 1;
  std::cout
    << "Hoge::Hoge(const Hoge& hoge): "
    << this->counter_
    << std::endl;
}
 
Hoge& Hoge::GetReference() {
  return *this;
}
 
Hoge Hoge::GetCopy1() {
  std::cout
    << "Hoge::GetCopy1(): begin: "
    << this->counter_
    << std::endl;
  Hoge copy = *this;
  std::cout
    << "Hoge::GetCopy1(): end: "
    << this->counter_
    << std::endl;
  return copy;
}
 
Hoge Hoge::GetCopy2() {
  std::cout
    << "Hoge::GetCopy2(): "
    << this->counter_
    << std::endl;
  return *this;
}
 
Hoge::~Hoge() {
  std::cout
    << "Hoge::~Hoge(): "
    << this->counter_
    << std::endl;
}

main.cpp


#include <iostream>
#include "Hoge.h"
 
int main() {
  std::cout << "----- hg -----------------------" << std::endl;
  Hoge hg;
  std::cout << "----- hr -----------------------" << std::endl;
  Hoge& hr = hg.GetReference();
  std::cout << "----- h1 -----------------------" << std::endl;
  Hoge h1 = hg.GetCopy1();
  std::cout << "----- h2 -----------------------" << std::endl;
  Hoge h2 = hg.GetCopy2();
  std::cout << "----- end -----------------------" << std::endl;
  return 0;
}

実行結果。


----- hg -----------------------
Hoge::Hoge(): 1
----- hr -----------------------
----- h1 -----------------------
Hoge::GetCopy1(): begin: 1
Hoge::Hoge(const Hoge& hoge): 2
Hoge::GetCopy1(): end: 1
----- h2 -----------------------
Hoge::GetCopy2(): 1
Hoge::Hoge(const Hoge& hoge): 2
----- end -----------------------
Hoge::~Hoge(): 2
Hoge::~Hoge(): 2
Hoge::~Hoge(): 1

tags: c++

Posted by NI-Lab. (@nilab)