2011-04-12 26 views
0

可能重複:
Easiest way to convert int to string in C++寫一個抽象的功能將整數轉換爲字符串

class MyInteger 
{ 
    MyInteger() : m_val(0) { } 
    MyInteger()(int _val) : m_val(_val) {} 
    ~MyInteger() {} 
}; 

MyInteger myInteger(10); 
std::string s = (std::string)myInteger 

我怎麼能寫C++函數s到獲得 「10」? 我是C++新手。

非常感謝。

+1

也 - 你不需要在你的情況下定義析構函數,默認是足夠的,而你沒有'm_val'成員。另外,通過像你一樣強制轉換'MyInteger'到'std :: string',你需要定義一個轉換操作符。或者你可以定義一個'to_string()'成員函數。 – davka 2011-04-12 17:40:20

回答

3

你可以有一個方法

#include <sstream> 
#include <string> 
//... 

std::string MyInteger::toString() 
{ 
    std::stringstream stream; 
    stream << m_val; 
    return stream.str(); 
} 

或以適合您的風格:

class MyInteger 
{ 
public: 
    MyInteger() : m_val(0) { } 
    MyInteger()(int _val) : m_val(_val) {} 
    ~MyInteger() {} 

    std::string toString() 
    { 
     std::stringstream stream; 
     stream << m_val; 
     return stream.str(); 
    } 

private: 
    int m_val; 
}; 
+0

+1更好。刪除了我的! – Nawaz 2011-04-12 17:40:54

1

除了上面的方法,你可以重載鑄造操作是這樣的:

class MyInteger 
{ 
    ... 
    operator std::string() { /* string conversion method here */ } 
}; 
如以下鏈接所述

Overload typecasts