2011-09-21 65 views
2

在GCC編譯器中創建一個新的字符串類併爲其分配一個char*的數組有一個奇怪的問題。源代碼:奇怪的賦值問題 - C++

#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是如何做他們的任務?

+0

發生在我設置StdString myStr中=; – IDWMaster

+0

請考慮在這裏發佈一個最簡單的工作示例。 –

+0

你爲什麼使用pastebin?代碼將適合在這裏。 –

回答

2

std :: string可以進行轉換,因爲它定義了一個conversion constructor。像這樣的東西。

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

注意:實際的std :: string更爲複雜。

隨着賦值運算符,你應該能夠做到

StdString str; 
str = "hello"; 

但不

StdString str = "hello"; 
+0

如果'StdString'更像'std :: string',那麼初始化也必須工作。 'std :: string'有一個重載的構造函數,其參數類型爲'const char *'。 [參考](http://www.cplusplus.com/reference/string/string/string/) – Mahesh

+0

謝謝!這原來是解決方案 – IDWMaster

0

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

0

爲什麼你定義的轉換操作符爲:

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

這一切都不會返回的other內容,無需設置當前類的internstr到其他給定的。

我會怎麼做,看起來更像是:

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

    return *this; 
} 
1

您遇到的錯誤是不提供一個構造函數一個char*。這是編譯器抱怨缺少的轉換函數。

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

另外,如果您的內部字符串是std::string,那麼你不需要任何賦值運算符,拷貝構造函數和析構函數。一旦添加char*轉換構造函數,編譯器提供的賦值運算符也將神奇地工作於char*。好吧,不是很神奇:編譯器會看到它可以通過轉換構造函數將char *轉換爲StdString,然後將其與隱式賦值運算符一起使用。

您也可以保留默認構造函數的定義爲空;這會給你所有成員的默認構造,這可能足夠好。

1

StdString mystr = "Hello world!";

需要複製構造函數。

嘗試添加以下內容: 「你好!世界」

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