为什么这里需要构造函数和赋值操作符

why do I need both constructor and assignment operator here?

本文关键字:赋值操作符 构造函数 这里 为什么      更新时间:2023-10-16

当省略其中一个时,我的代码无法编译。我认为在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";首先用"Hello world"创建一个临时AString,然后将first分配给它。

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