2

Let's say I have a function called dummy defined in the following way:

void dummy(CMyString& mystr)
{
   mystr.print(); //show
}

CMyString would be my own implementation of strings using an array of chars.

int main()
{
   dummy("This is a test!");
   return 0;
}

I'd like the following program to print out : "This is a test!". Is this possible?

fire xzanderr
  • 213
  • 2
  • 13

2 Answers2

3

Yes it is, you just need to provide a non-explicit conversion constructor to CMyString:

class CMyString
{
public:
    CMyString(const char* x); 
    //.....
};

and, of course, implement the CMyString::print method. After this you need to change the parameter to

void dummy(const CMyString& mystr)

(and mark the print method as const) because you can't bind a temp to a non-const reference.

Chowlett
  • 45,935
  • 20
  • 116
  • 150
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

Certainly. You just need to define a constructor for CMyString that takes an array of chars or a pointer to char as its sole argument. Like so:

class CMyString
{
public:
  CMyString(const char* str)
  {
    // Initialise CMyString with str
  }
};
Chowlett
  • 45,935
  • 20
  • 116
  • 150