이 질문을 다른 곳에서 묻고 애매한 대답을 얻었습니다. 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
를 사용하는 저를 알렸다에 내가 물었다하지만이 같은 수행 할 때
http://pastebin.com/UawrwYj7 :
이
conversion from
‘std::string* {aka std::basic_string *}’
to non-scalar type‘std::string {aka std::basic_string }’
requested
전체 소스는 여기에 있습니다 :
string toReturn = new string;
그것은 나에게 오류를 제공
샘플 실행 결과는 다음과 같습니다.
Type: Birch
Age:
Height:
Width:
Weight: d
Generic name:
State of Matter: solid
Flammable:
가장 좋은 방법은 C++에서 new'가에 있지'사용 모든. 언어가 그렇게 작동하지 않습니다. –
note :'string getStats()'(아마도 OO ..)를 원할 것입니다. btw 원래 코드의 문제점은 무엇입니까? 왜'new'를 사용하고 싶습니까? –
코드가 완벽하게 유용합니다. ** 새로운 사용 **은 절대적으로 필요하지 않습니다 **. 이 코드가 올바르게 작동합니까? –