为什么我在这里需要构造函数和赋值运算符?

时间:2013-05-08 21:08:39

标签: c++ copy-constructor assignment-operator

当省略其中一个代码时,我的代码无法编译。我认为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 )创建的?

1 个答案:

答案 0 :(得分:4)

second = first = "Hello world";首先使用AString创建一个临时"Hello world",然后为其分配first

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