当省略其中之一时,我的代码无法编译。我认为这里只需要复制赋值运算符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 )
?