각종 구조 함 수 를 깊이 이해 하 다.

#include<string.h>
#include<iostream>
using namespace std;

class test{
public:
    test(char *p ){

        cout << "this is construction of test"<< p << endl;

        if(p){
            pData = new char[strlen(p)+1];
            strcpy(pData, p );
        }
        else
        {
            pData = new char[1];
            *pData = '\0';

        }
    }
    test(const test & T){

        cout <<" this is copy construction of test " << T.pData<< endl;

        if(T.pData){
            pData = new char [strlen(T.pData)+1];
            strcpy( pData , T.pData);
        }
        else
        {
            pData = new char [1] ;
            *pData = '\0';
        }
    }
	
    test &operator = (const test & T){
		
        cout << "this is operator = :" << pData <<"=" << T.pData << endl ;
		
        if(this == &T)
            return *this;
		
        if(T.pData)
        {
            if(pData){
                delete [] pData;
            }
            pData = new char [strlen(T.pData) + 1];
            strcpy(pData , T.pData);
        }
        else
        {
            pData = new char[1];
            *pData = '\0';
        }
        return * this;
    }
	
    ~test(){
		
        cout << "this is dectruction of test "<< pData << endl ;
		
        delete [] pData;
    }
	void set( char*value)
	{
		if(value)
		{
			delete [] pData;
			pData = new char [strlen(value) + 1];
			strcpy(pData , value);
		}
	else
	{
		pData = new char[1];
		*pData = '\0';
        }

	}
	
private:
    char * pData;
};


 test fun( test Aa){  
        test Bb("    0000") ;  
        Bb = Aa ;
		Bb.set("    2222");
        return Bb ;  
    }  
  
  
  
 int main()
 {  
	 test A("    1111");  
	 test B = fun( A ) ;  
	 
	 test C = A ;  
	 A = B;
	 
 }  

 
실행 결 과 는 다음 과 같 습 니 다.
this is construction of test    1111     //A 의 구조 함수 this is copy construction of test     1111    //전송 값 이 발생 한 결과, 즉 A 가 Aa this is construction of test 를 복사 한 것 입 니 다.    0000    //Bb 의 구조 함수 this is operator =:    0000=    1111    //Bb = Aa 의 결과 this is copy construction of test     2222    //return Bb;Bb 로 B 를 구 조 했 기 때문에 복사 구조 함수 this is dectruction of test 를 호출 했 습 니 다.     2222     //Bb 의 석조 함수 this is dectruction of test     1111    //Aa 의 분석 함수 this is copy construction of test     1111    //구문 Test C = A 의 구조 함수, 여 기 는 operator = 를 호출 하지 않 았 습 니 다. 복사 구조 함수 의 효율 이 더욱 높 기 때문에 this is operator = 를 최적화 한 셈 입 니 다.    1111=    2222    //A = B 조작 결과 this is dectruction of test     1111    //C 의 석조 함수 this is dectruction of test     2222    //B 의 석조 함수 this is dectruction of test     2222    //A 의 석조 함수 Press any key to contine
 
속담 에 이 르 기 를 기억력 이 썩 은 필치 보다 못 하 다 고 했 는데, 자기가 쓴 코드 를 이 제 는 알 아 보지 못 하 다 니.............................................

좋은 웹페이지 즐겨찾기