티스토리 뷰

Reading Books/Accelerated C++

Chapter. 10

DWGoon 2009. 7. 29. 17:15

<const도 일종의 매개 변수라는 것>
class Test {

public:      
	
	// const가 아닌 Test 객체에 적용할 때
	void operator[](size_t i) {       
		cout << "나는 그냥 [] 연산자" << endl;  
	}            
	
	// const인 Test 객체에 적용할 때    
	void operator[](size_t i) const{          
		cout << "나는 const [] 연산자" << endl;             
	}      
};



<복사 생성자 및 대입 연산자의 호출>

#include 
#include 
using namespace std;


class Test {         

	string name;      
	const Test* st;    

public:      

	Test() {} // default ctor is a ctor which has no parameter.  

	Test(const string& s) {     
		cout << &name << "의 복사 생성자" << endl;     
		cout << "(" << &s << "가 전달인자로 들어왔다)" << endl;   
		cout << "(내용 :" << s << ")" << endl << endl;          
		name = s;  
	}       

	Test(const Test& t) {  
		cout << &name << "의 복사 생성자" << endl;      
		cout << "(" << &(t.name) << "가 전달인자로 들어왔다)" << endl;    
		cout << "(내용 :" << t.name << ")" << endl << endl;     
		name = t.name;                       
		func(t);    
	}            


	void func(const Test& t) {          
		st = &t;            
		cout << "func() : " << &t << "가 들어왔다" << endl;    
		cout << "(내용 :" << t.name << ")" << endl  << endl;     
	}              
	void showSt() {        
		cout << &name << "의 st는 " << &(st->name) << endl;   
		cout << "(내용 :" << st->name << ")" << endl  << endl;    
	}         

	void setName(const string& s) { name = s; }   

	const string& getName() const { return name; }  

	void operator[](size_t i) {        
		cout << "나는 그냥 [] 연산자" << endl;    

	}            

	void operator[](size_t i) const{    
		cout << "나는 const [] 연산자" << endl;    
	}             


	Test& operator=(const Test& t) {     
		cout << &name << "의 대입 연산자" << endl;       
		cout << "(" << &(t.name) << "가 전달인자로 들어왔다)" << endl;  
		cout << "(내용 :" << t.name << ")" << endl  << endl;          
		if (this != &t) {             
			name = t.name;           
		}             

		return *this;      
	}      
};


inline Test getTest(Test t) { 
	cout << &t << "는 getTest의 전달인자" << endl << endl;    
	return t;   

}


int main(int argc, char *argv[]) {  

	Test t;    
	t.setName("good");    
	Test t2;  
	t2 = t;  
	Test t3 = getTest(t2);     
	t3.showSt();       
	getTest(Test("very good"));       
	t3.showSt();     


	system("PAUSE");    
	return EXIT_SUCCESS;

}





Result of Dev-C++ 5.0 beta 9.2 (4.9.9.2) (9.0 MB) with Mingw/GCC









Result of MSVC 2008




- getTest의 호출을 마친 후, 포인터로 getTest의 매개변수에 접근을 시도하는 부분에서 당연히 문제가 발생해야 한다.
하지만 Dev-C++의 gcc는 이같은 접근을 허용하여 어떠한 에러 메시지도 던지지 않지만 MSVC 2008은 런타임 에러를 일으킨다.


'Reading Books > Accelerated C++' 카테고리의 다른 글

Chapter. 9  (0) 2009.07.28
Chapter. 6  (0) 2009.07.09
Chapter. 5  (0) 2009.07.02
Chapter. 4  (0) 2009.06.29
Chapter. 2, 3  (0) 2009.06.26
댓글