Мой код не компилируется, когда один из них опущен. Я думал, что здесь требуется только оператор присваивания копий в 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 второй (первый); ' –
Ваш код компилируется в g ++ 4.7 и 4.8 ... – dyp
с копией и присваиванием ... – 4pie0