[英]C++ function not returning properly: string destructor being called
我在其他地方問過這個問題並得到了模糊的答案,我認為這是因為我不了解如何使用new
關鍵字。
我正在從事的項目只是為了幫助我開始學習C ++,但是我來自Java方面的知識。 它只是我最終將在基於文本的游戲中使用的結構和功能的集合。
我遇到麻煩的函數是getStats()
,它將返回結構木及其繼承結構的變量的某些值。
/**
*Returns information regarding the status of the wood.
*@param the wood to retrieve.
*@return A string representing the stats.
*/
string getStats(wood toGet)
{
string toReturn;
//Substruct specific variables.
toReturn += "Type: ";
toReturn += toGet.type;
toReturn += "\nAge: ";
toReturn += toGet.age;
//Superstruct variables.
toReturn += "\nHeight: ";
toReturn += toGet.height;
toReturn += "\nWidth: ";
toReturn += toGet.width;
toReturn += "\nWeight: ";
toReturn += toGet.weight;
toReturn += "\nGeneric name: ";
toReturn += toGet.name;
toReturn += "\nState of Matter: ";
toReturn += toGet.stateOfMatter;
toReturn += "\nFlammable: ";
toReturn += toGet.flammable;
toReturn += "\n";
return toReturn;
}
我意識到我現在正在以一種愚蠢的方式執行此操作,我將使用數組和循環對其進行重做,但是現在我正在使用此方法。 在另一個網站上,我問他們是否要求我使用new
,但是當我這樣做時:
string toReturn = new string;
它給我一個錯誤:
請求從
'std::string* {aka std::basic_string *}'
轉換為非標量類型'std::string {aka std::basic_string }'
完整的源代碼在這里: http : //pastebin.com/UawrwYj7
樣本運行的輸出如下。
類型:樺木
年齡:
高度:
寬度:
重量:d
通用名:
物質狀態:穩定
易燃:
1)您不需要new
。 C ++不是Java。 在C ++中,對象在聲明時就存在。
2)表達式w.getStats(w)
是多余的。 您無需將w
作為參數傳遞,它作為this
指針隱式傳遞。
3)您不能這樣做:
double x;
toReturn += x;
沒有std::string operator+= (double)
。 在最新版本的C ++標准之前, std::string
類通常不進行格式化。 如果您有足夠新的編譯器,則可以用以下代碼替換height
, width
, weight
等代碼:
double x;
toReturn += std::to_string(x);
但是,我建議您使用運算符<<
。 這將允許您根據使用方式設置字符串格式或將數據發送到文件。
這是您更新的getStats
:
// Untested code
std::string getStats()
{
std::ostringstream oss;
oss << "Type: " << this->type << "\n";
oss << "Age: " << this->age << "\n";
oss << "Height: " << this->height << "\n";
oss << "Width: " << this->width << "\n";
// and so on
return oss.str();
}
稍后,當您學習如何覆蓋operator<<
,請嘗試以下方法:
friend std::ostream& operator<<(std::ostream& os, const wood& w) {
os << "Type: " << w.type << "\n";
os << "Age: " << w.age << "\n";
os << "Height: " << w.height << "\n";
os << "Width: " << w.width << "\n";
// and so on
return os;
}
std::string getStats() {
std::ostringstream oss;
oss << *this;
return oss.str();
}
當調用原始版本時,將首先構造,填充字符串,然后將返回副本,並且原始字符串(位於getStats()
的堆棧上)將被銷毀。
new string;
返回一個指向字符串的指針 ,而不是字符串對象,因此保存它的變量必須是指針string *
,而不是string
。 但是,這涉及動態內存管理-在這種情況下,您不希望這樣做。
簡介:因為C ++與Java確實不同,所以用C ++做任何事情,都需要看一本不錯的書,並且至少要學習一些基礎知識。
編輯 :同樣,為了使您的函數正常工作,請閱讀有關stringstream
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.