Humaneer
2014년 12월 23일 화요일
operator= 는 자기대입 처리할 것, 객체는 빠짐없이 복사할 것.
effective c++, chapter 11
#include
#include
#include
#include
#include
#include
struct GenRand { template
void operator()(T& rhs) { rhs = static_cast
(rand() % 255); } }; struct TransRand { template
T operator()(const T& rhs) { return (rand() % 255) * rhs; } }; class Widget { protected: int _count; friend std::ostream& operator << (std::ostream& os, const Widget& rhs); virtual void swap(Widget& rhs) { std::cout << "Widget Swap...\n"; int tempCount = _count; int* tempData = _data; _count = rhs._count; _data = rhs._data; rhs._count = tempCount; rhs._data = tempData; } int* _data; public: ~Widget() { if(_count) delete [] _data; std::cout << "Widget Destroy...\n"; } Widget(const int& count = 0) : _count(count), _data(0) { std::cout << "Widget Create Default...\n"; if (_count) { _data = new int[_count]; std::for_each(_data, _data+_count, GenRand()); } } Widget(const Widget& rhs) : _count(rhs._count) { std::cout << "Widget Create Copy...\n"; _data = new int[_count]; std::copy(rhs._data, rhs._data+rhs._count, _data); } Widget& operator=(Widget rhs) { std::cout << "Widget Assign...\n"; swap(rhs); return *this; } }; std::ostream& operator << (std::ostream& os, const Widget& rhs) { std::copy(rhs._data, rhs._data+rhs._count, std::ostream_iterator
(os, " ")); os << "\n"; return os; } class WidgetDerived : public Widget { private: float* _fdata; public: friend std::ostream& operator << (std::ostream& os, const WidgetDerived& rhs); ~WidgetDerived() { std::cout << "WidgetDerived Destroy...\n"; if (_count) delete [] _fdata; } WidgetDerived(const int& count = 0) : Widget(count) { std::cout << "WidgetDerived Create Default...\n"; if (_count) { _fdata = new float[_count]; std::transform(_data, _data+_count, _fdata, TransRand()); } } WidgetDerived(const WidgetDerived& rhs) : Widget(rhs) { std::cout << "WidgetDerived Create Copy...\n"; _fdata = new float[_count]; std::copy(rhs._fdata, rhs._fdata+rhs._count, _fdata); } virtual void swap(WidgetDerived& rhs) { Widget::swap(rhs); std::cout << "WidgetDerived Swap...\n"; float* tempFData = _fdata; _fdata = rhs._fdata; rhs._fdata = tempFData; } WidgetDerived& operator=(WidgetDerived rhs) { std::cout << "Widget Assign...\n"; swap(rhs); return *this; } }; std::ostream& operator << (std::ostream& os, const WidgetDerived& rhs) { os << (Widget&)rhs; std::copy(rhs._fdata, rhs._fdata+rhs._count, std::ostream_iterator
(os, " ")); return os; } int main() { //WidgetDerived wd(5); //wd = wd; //Widget a(5); srand(time(NULL)); WidgetDerived wd(5); std::cout << wd << "\n\n"; WidgetDerived b = wd; b = b; std::cout << b << "\n"; return 0; }
댓글 없음:
댓글 쓰기
최근 게시물
이전 게시물
홈
피드 구독하기:
댓글 (Atom)
댓글 없음:
댓글 쓰기