2013-05-08 3 views
0

이 중 하나를 생략하면 내 코드가 컴파일되지 않습니다. main()에 복사 할당 연산자 만 필요하다고 생각했습니다. 생성자도 어디에서 필요합니까?왜 생성자와 할당 연산자가 모두 필요합니까?

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

class AString{ 
    public: 
     AString() { buf = 0; length = 0; } 
     AString(const char*); 
     void display() const {std::cout << buf << endl;} 
     ~AString() {delete buf;} 

AString & operator=(const AString &other) 
{ 
    if (&other == this) return *this; 
    length = other.length; 
    delete buf; 
    buf = new char[length+1]; 
    strcpy(buf, other.buf); 
    return *this; 
} 
    private: 
     int length; 
     char* buf; 
}; 
AString::AString(const char *s) 
{ 
    length = strlen(s); 
    buf = new char[length + 1]; 
    strcpy(buf,s); 
} 

int main(void) 
{ 
    AString first, second; 
    second = first = "Hello world"; // why construction here? OK, now I know : p 
    first.display(); 
    second.display(); 

    return 0; 
} 

이이

여기 때문에
second = first = "Hello world"; 

첫째는 일시적이 AString::AString(const char *s)에 의해 생성된다 ?

+0

이것은'second = first/* = "Hello world"* /;'복사 생성자에서만 다음과 같이 할 수 있습니다 :'AString first ("Hello world"); AString second (first); ' –

+0

코드가 g ++ 4.7 & 4.8 ... – dyp

+0

에서 복사 및 할당이 모두 잘되어 컴파일됩니다. – 4pie0

답변

4

second = first = "Hello world"; 먼저 "Hello world"과 함께 AString을 생성 한 다음 first이 할당됩니다.

AString::AString(const char *s)이 필요하지만 복사 생성자가 아닙니다.

+0

[expr.ass]/1 "대입 연산자 (=)와 복합 대입 연산자는 모두 오른쪽에서 왼쪽으로 그룹화됩니다." – dyp

+0

네, 정확하게, 저는 질문을 업데이트했습니다. 나는 일시적인 것을 간과했습니다. 방법을 묻지 마라. – 4pie0

+2

보통 한개의 arg를 '명시 적으로'추천 한 생성자를 표시했다면,이 코드는 여러분이 예상 한 에러를 주었을 것입니다. –