簡體   English   中英

為什么在這里需要構造函數和賦值運算符?

[英]why do I need both constructor and assignment operator here?

當其中之一被省略時,我的代碼無法編譯。 我認為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"; 首先創建一個temporay AString"Hello world" ,那么first被分配給它。

因此,您需要AString::AString( const char *s ) ,但它不是副本構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM