본문 바로가기

과제모음

[C++]복사생성자

반응형

>>연습문제 1<<

#include <iostream>
#include "CpCons.h"
using std::cout;

class Date
{
public:
    Date(int yy, int mm, int dd);
    outDate()const;
   
    Date(const Date &date);
    
private:
    int year;
    int month;
    int day;
};

int main()
{
    Date d1(2007, 3, 4);
    Date d2(1994, 2, 19);

    d1.outDate();
    d2.outDate();

    Date d3(d1);
    d3.outDate();

    return 0;
}

Date::Date(int yy, int mm, int dd)
{
    year = yy;
    month = mm;
    day = dd;
}

Date::outDate() const
{
    cout <<"\n" << year << " / " <<month << " / " << day << "\n";
}

Date::Date(const Date &date)
{
    this->year = date.year;
    this->month = date.month;
    this->day = date.day;
    cout << "복사생성자";
}

>>연습문제 2<<

#include <iostream>
#include <string.h>
using std::cin;
using std::cout;
using std::endl;

class MyString{
public:

    MyString(char *p);
    void show()const;
    MyString(const MyString &str);
    ~MyString();

private:
    char *pstr;
};

int main()
{
    MyString s1="apple";
    MyString s2="Hello World";
    MyString s3=s1;
    MyString s4=s2;

    s1.show();
    s2.show();
    s3.show();
    s4.show();

    return 0;
}


MyString::MyString(char *p)
{
    this->pstr = new char[strlen(p)+1];
    strcpy(pstr, p);
    cout << "생성자 호출\n";
}
void MyString::show()const
{
    cout << pstr << endl;
}
MyString::MyString(const MyString &str)
{
    this->pstr = new char[strlen(str.pstr)+1];
    strcpy(pstr, str.pstr);
    cout << "복사 생성자 호출\n";
}

MyString::~MyString()
{
    delete [] pstr;
    cout << "소멸자 호출\n";
}


반응형

'과제모음' 카테고리의 다른 글

[C++]Inheritance(상속)  (0) 2010.01.22
[C++]복사생성자2  (0) 2010.01.22
[C++]Const & this & Static 변수  (0) 2010.01.22
[C++]상수(Const)  (0) 2010.01.22
[C++]소멸자2(Destructor)  (0) 2010.01.22