0

Possible Duplicate:
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 

How can I write C++ function to get "10" in s?? I am new to C++.

Thanks you very much.

Community
  • 1
  • 1
Mnop492
  • 53
  • 1
  • 2
  • 4
  • 1
    also - you don't need to define the destructor in your case, the default is enough, and you don't have the `m_val` member. Also, to convert `MyInteger` to `std::string` by casting as you do you need to define a casting operator. Or you can define a `to_string()` member function. – davka Apr 12 '11 at 17:40

2 Answers2

3

you could have a method

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

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

or to fit your style:

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;
}; 
1

In addition to the above methods you can overload the casting operator like this:

class MyInteger
{
  ...
  operator std::string() { /* string conversion method here */ }
};

as stated in the following link Overload typecasts

Yet Another Geek
  • 4,251
  • 1
  • 28
  • 40