私はこの質問を他の場所で尋ねてきましたが、あいまいな答えを得ました。これはnew
キーワードの使い方を理解できないためです。C++関数が正常に返されない:文字列デストラクタが呼び出されている
私が取り組んでいるプロジェクトは、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;
それは私にエラーを与える:
conversion from
‘std::string* {aka std::basic_string *}’
to non-scalar type‘std::string {aka std::basic_string }’
requested
完全なソースはこちらです:http://pastebin.com/UawrwYj7
サンプル実行からの出力は以下のとおりです。
Type: Birch
Age:
Height:
Width:
Weight: d
Generic name:
State of Matter: solid
Flammable:
C++に 'new'を使用する最良の方法はではなく、すべて。言語はそのようには機能しません。 –
注:おそらく 'string getStats()'が必要です(それはオブジェクト指向です)。 btw元のコードの問題点は何ですか?なぜあなたは 'new'を使いたいのですか? –
あなたが持っているコードは完全に便利です。 **新しく**を使う必要は全くありません**。このコードは正しく動作していますか? –