클래스 접근????

nayana의 이미지

c만 하다가 c++ 공부를 하고 있습니다.
소스는 다음과 같습니다.

#include <iostream>
#include <cstring>

using namespace std;

class String
{
    int   m_slen;
    char* m_pstr;

    String( const String& s ) {};
    String& operator=( const String &s )
    {
    	return *this;
    }
    
public :
    String( const char* s = 0 );
    ~String();
    void copy( const String& s );
    friend void add( const String &s, const String &t, String *u );
    friend ostream& operator << ( ostream& os, const String& s );
};

String::String( const char *s )
{
    m_slen = s ? strlen( s ) : 0;
    m_pstr = new char[m_slen + 1];
    if ( s ) strcpy( m_pstr, s );
}

String::~String()
{
    delete []m_pstr;
}

void String::copy( const String &s )
{
    if ( this == &s )   return;
    delete []m_pstr;
    m_slen = s.m_slen;
    m_pstr = new char[m_slen + 1];
    strcpy( m_pstr, s.m_pstr );
}

void add( const String &s, const String &t, String *u )
{
    delete []u->m_pstr;
    u->m_slen = s.m_slen + t.m_slen;
    u->m_pstr = new char[u->m_slen + 1];
    strcpy( u->m_pstr, s.m_pstr );
    strcat( u->m_pstr, t.m_pstr );
}

ostream& operator << ( ostream& os, const String& s )
{
    return os << s.m_pstr;
}

int main ( void )
{
    String s1 = "C++";
    String s2 = "JungBok";
    String s3;
    //String s4 = s1; //cannot access private member
    //s3 = s1;        //cannot access private member
    
    s3.copy( s1 );
    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
    cout << "s3: " << s3 << endl;
    
    add( s1, s2, &s3 );
    cout << "add( s1, s2, &s3 ); s3: " << s3 << endl;
    
    return 0;
}

    
    

에러는 다음과 같습니다.

big3-04.cpp: In function `int main()':
big3-04.cpp:11: `String::String(const String&)' is private
big3-04.cpp:62: within this context
big3-04.cpp:62:   initializing temporary from result of `String::String(const
   char*)'
big3-04.cpp:11: `String::String(const String&)' is private
big3-04.cpp:63: within this context
big3-04.cpp:63:   initializing temporary from result of `String::String(const
   char*)'

에러코드를 보니까.... 복사 생성자를 public 으로 두면 양호한데...
이와같은 에러가 나는 이유가 이해가 되지 않습니다.
62,63 라인 둘다 public 으선언된 생성자를 호출하는것이 아닌가요...
vc++ 돌려보면 컴파일이 잘됩니다.
dyks의 이미지

    String s1 = "C++";
    String s2 = "JungBok";

이부분을

    String s1( "C++" );
    String s2( "JungBok" );

이런 코드와 혼동하신게 아닌가 합니다.

    String s1 = "C++";

이 코드는, String( "C++" ) 이라는 임시객체를 생성하고, 그 객체를
String::String( const String & ) 생성자를 이용해 생성하는 코드 입니다.
대입 연산자( = )이 있으니, 당연히 대입 생성자가 호출이 되었겠지요.

다른 컴파일러에서 잘 동작한다면, 해당 컴파일러가 문제가 있는 겁니다.^_^