2013-05-11 65 views
2

我想使用boost :: lexical_cast將我的用戶定義類型轉換爲整數。 但是,我得到一個異常。我在想什麼?詞彙從用戶定義類型轉換爲int

class Employee { 
private: 
    string name; 
    int empID; 

public: 
    Employee() : name(""), empID(-1) 
    { } 

    friend ostream& operator << (ostream& os, const Employee& e) { 
     os << e.empID << endl;  
     return os; 
    } 
    /* 
    operator int() { 
     return empID; 
    }*/ 
}; 

int main() { 
    Employee e1("Rajat", 148); 
    int eIDInteger = boost::lexical_cast<int>(e1); // I am expecting 148 here. 
    return 0; 
} 

我知道我總是可以使用轉換操作符,但只是想知道爲什麼詞法轉換在這裏不起作用。

回答

0

問題是,您插入到輸出流中的不是整數的表示(因爲尾隨<< std::endl)。下面以類似的方式失敗:

boost::lexical_cast<int>("148\n") 

卸下<< std::endl使得它的工作:

friend std::ostream& operator << (std::ostream& os, const Employee& e) { 
    os << e.empID; 
// ^^^^^^^^^^^^^^ 
// Without << std::endl; 

    return os; 
} 
+0

日Thnx很多..愚蠢的錯誤:-)我的一部分。 – 2013-05-12 06:42:09

+0

@RajatGirotra:很高興幫助:) – 2013-05-12 08:46:59