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 )?

4

1 回答 1

4

second = first = "Hello world";首先创建一个带有 的临时文件AString"Hello world"然后first分配给它。

所以你需要AString::AString( const char *s ),但它不是复制构造函数。

于 2013-05-08T21:18:59.130 回答