4 가지 멤버 함수가 있는 클래스 형태이다. 4가지가 필수는 아니다. 하지만 있으면 좋다고 한다. 왜 있어야 좋은지 차차 프로그램을 만들어보며 생각해보자.
#include "Sample.class.hpp"
#include <iostream>
Sample::Sample(void) : _foo(0) {
std::cout << "Sample created. Default." << std::endl;
}
Sample::~Sample(void) { std::cout << "Sample destroyed." << std::endl; }
Sample::Sample(int const n) : _foo(n) {
std::cout << "Parametric Constructor called" << std::endl;
}
Sample::Sample(const Sample& src) {
std::cout << "Copy constructor called." << std::endl;
*this = src;
}
Sample& Sample::operator=(const Sample& rhs) {
std::cout << "Assignment operator called" << std::endl;
if (this != &rhs) {
this->_foo = rhs.getFoo();
}
return *this;
}
std::ostream & operator<<(std::ostream &o, Sample const & i) {
o << "The value of _foo is : " << i.getFoo();
return o;
}
int Sample::getFoo(void) const { return this->_foo; }
#ifndef SAMPLE_CLASS_HPP
# define SAMPLE_CLASS_HPP
# include <iostream>
class Sample {
private:
int _foo;
public:
Sample(void); // Canonical form 생성자
Sample(int const n);
Sample(Sample const& src); // Canonical form 복사 생성자
~Sample(void); // Canonical form 소멸자
Sample& operator=(Sample const& rhs); // Canonical form 대입 연산자 오버로딩
int getFoo(void) const;
};
std::ostream& operator<<(std::ostream& o, Sample const& i);
#endif
#include <iostream>
#include "Sample.class.hpp"
int main(void) {
Sample instance1;
Sample instance2(42);
Sample instance3(instance1);
std::cout << instance1 << std::endl;
std::cout << instance2 << std::endl;
std::cout << instance3 << std::endl;
instance3 = instance2;
std::cout << instance3 << std::endl;
return (0);
}