C++ 생성자 질문입니다.

kknd345의 이미지

#include <iostream.h>
#include <string.h>

class Str{
private:
	char * p_str;	

public:

	Str(){
		p_str=NULL;
	}

	Str( char* s)
	{
		p_str=new char[strlen(s)+1];
		strcpy(p_str,s);
	}

	Str( const Str& CStr)
	{
		p_str=new char[ strlen( CStr.getstr() )+1];
		strcpy(p_str, CStr.getstr() );
	}

	char* getstr()
	{
		return p_str;
	}

};





int main()
{
	Str a1;
	Str a2("haha");
	Str a3( a2 );

	//cout << a1.getstr() << endl;
	cout << a2.getstr() << endl;
	cout << a3.getstr() << endl;

                return 0;
}

Quote:
haha.cpp(22) : error C2662: 'getstr' : cannot convert 'this' pointer from 'const class Str' to 'class Str &'
Conversion loses qualifiers
haha.cpp(23) : error C2662: 'getstr' : cannot convert 'this' pointer from 'const class Str' to 'class Str &'
Conversion loses qualifiers

이런 에러가 납니다. 그래서 CStr.p_str 이렇게 고치니깐 되기는 되는데.... 왜 저렇게 고쳐야 되나요?
그리고 CStr의 멤버 데이터(private)에 이렇게 접근이 왜 가능한건가요?

yielding의 이미지

1. const객체의 non-const 멤버함수를 호출할때 발생하는 문제입니다.
char* getstr() const {}로 바꾸거나 아님 2의 방법 사용

2. 동일한 클래스에 속하는 타입의 인스턴스를 멤버함수의 인자로 받을 경우 private 멤버변수를 접근할 수 있습니다.
그래서 copy constructor, assignment operator 에서 private변수를 곧바로 access하는것을 흔히(일반 멤버 함수에도 동일하게 적용) 볼 수 있습니다.

Life rushes on, we are distracted