이 중 하나를 생략하면 내 코드가 컴파일되지 않습니다. 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)
에 의해 생성된다 ?
이것은'second = first/* = "Hello world"* /;'복사 생성자에서만 다음과 같이 할 수 있습니다 :'AString first ("Hello world"); AString second (first); ' –
코드가 g ++ 4.7 & 4.8 ... – dyp
에서 복사 및 할당이 모두 잘되어 컴파일됩니다. – 4pie0