1

If I have my own SString class in c++ and I want to be able to do this:

SString x("text"); LPCSTR p = (LPCSTR)x; cout<<p; 

How do I do it?

3
  • side note: better use static_cast<LPCTSTR>(x); always prefer c++ style casts over c style casts; they're easier to spot, and they're more restricted in what they can do, so there's less chance of errors creeping in by casting! Commented Sep 18, 2012 at 9:46
  • You could overload std::ostream operator<<(std::ostream&, const SString&) instead Commented Sep 18, 2012 at 9:46
  • thank you, but I am also very interested in the casting part. Commented Sep 18, 2012 at 11:13

2 Answers 2

5

Create conversion operator to LPCSTR in your class SString. If you can use C++11 this operator should be explicit.

operator LPCSTR() const { /*return data*/ }; 

Also you can create some function like (i think this variant is better, than conversion operator)

LPCSTR asLPCSTR() const { /*return data*/ }; 
Sign up to request clarification or add additional context in comments.

Comments

3

In addition to what ForEveR said, note that you can also overload

ostream& operator << (ostream& str, const SString& ss); 

and call

cout<<x; 

directly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.