爲什麼你的代碼編譯,但給無意義的結果已經explained by adpalumbo。您的代碼中存在導致該錯誤的兩個基本問題,我想在此處進行擴展。
一個是你使用C風格演員:(T)obj
。基本上,這只是告訴編譯器閉嘴,你知道你在做什麼。這絕非一個好主意,因爲當你知道自己在做什麼時,通常可以不用這樣的演員。
另一個問題是您正在使用在堆上動態分配的對象。在C++中,應該在堆棧上創建對象,除非您有充分理由使用動態對象。動態對象通常隱藏在堆棧中的對象內。所以,你的代碼應該這樣寫:
string lati(data.substr(0, data.find_first_of(",")));
double latDub = /* somehow create double from lati */;
this->latitude = latDub;
當然,latDub
是完全沒有必要的,你也可以同樣寫this->latitude
直接。
現在,將字符串轉換爲其他類型的常用方法是通過字符串流進行流式處理。刪除您介紹了不必要的變數,您的代碼會再看看這樣的:
std::istringstream iss(data.substr(0, data.find_first_of(",")));
if(!iss >> this->latitude) throw "Dude, you need error handling here!";
通常要打包從一個字符串轉換成一個實用的功能,你可以在你的代碼重用:
inline double convert3double(const std::string& str)
{
std::istringstream iss(str);
double result;
if(!iss >> result)
throw std::exception("Dang!");
return result;
}
然而,由於非常相同的算法,可用於所有類型(其operator>>
與輸入流作爲左操作數有意義過載),只是使之成爲一個模板:
template< typename T >
inline T convert3double(const std::string& str)
{
std::istringstream iss(str);
T result; // presumes default constructor
if(!iss >> result) // presumes operator>>
throw std::exception("Dang!");
return result;
}
來源
2011-09-18 20:33:15
sbi
爲什麼你這麼用'new'?爲什麼使用'new'來分配所有東西的'std :: string'和**'double' **? –
@尼科爾:可能是因爲他被所謂的「純粹的」OO語言所毒化,所有這些都是「新鮮的」。 – sbi
Logan,在C++中是無意義的代碼。你很少在C++中使用'new'數據,當你這樣做時,它應該隱藏在一些非動態變量中。 – sbi