簡體   English   中英

奇怪的分配問題-C ++

[英]Strange assignment problem - C++

在GCC編譯器中創建一個新的字符串類並為其分配一個char*數組時遇到一個奇怪的問題。 源代碼:

#include "../Include/StdString.h"

StdString::StdString()
{
    //ctor
    internstr = std::string();
}

char* StdString::operator=(StdString other) {
    return other.cstr();
}

StdString StdString::operator+(StdString other) {
    StdString newstr = StdString();
    newstr.internstr = internstr+other.internstr;
    return newstr;
}

void StdString::operator=(char* other) {
    internstr = other;
}

StdString::~StdString()
{
    //dtor
}

char* StdString::cstr() {
    return (char*)internstr.c_str();
}

錯誤:請求從char*轉換為非標量類型StdString

std::string如何進行分配?

std :: string可以進行轉換,因為它定義了一個轉換構造函數 這樣的事情。

class std::string {
  // ...
std::string(const char *);
};

注意:實際的std :: string更復雜。

使用賦值運算符,您應該可以

StdString str;
str = "hello";

但不是

StdString str = "hello";

您遇到的錯誤是未提供采用char*的構造函數。 這是編譯器抱怨缺少的轉換功能。

StdString::StdString(char const* s)
{
    // ...
}

同樣,如果內部字符串是std::string則不需要任何賦值運算符,復制構造函數和析構函數。 一旦添加了char*轉換構造函數,編譯器提供的賦值運算符也將神奇地適用於char* 好吧,這並不是真正的魔術:編譯器將看到它可以通過轉換構造函數將char *轉換為StdString ,然后將其與隱式賦值運算符一起使用。

您也可以將默認構造函數的定義留空; 這將為您提供所有成員的默認構造,這可能已經足夠了。

StdString mystr =“世界你好!”;

需要復制構造函數。

嘗試添加以下內容:

StdString::StdString(const char* other)
{
    internstr = other;
}

看起來您在混淆分配和初始化。 初始化使用構造函數,即使使用“ =”符號調用也是如此。

為什么將轉換運算符定義為:

char* StdString::operator=(StdString other) 
{ 
    return other.cstr(); 
} 

所有這些操作確實返回了other的內容,而沒有將當前類的internstr設置為internstr給定的內容。

我會做的看起來更像是:

StdString& StdString::operator=(StdString other) 
{ 
    //  copy contents of other to this->internstr

    return *this;
} 

暫無
暫無

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

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