0

I have defined a class,

Aims: simulate the string but with more functionalities

class ex_char
{
public:
    ex_char(char *input):len(strlen(input)){strcpy(str,input);}
    ...functions...
private:
    char *str; //where the char array is saved
    int len;   //length of the char array
};

For a normal char array, we can use:

char charray[10]="String";
cout<<charray;

to show the content of the char array

But how can I show the content of my class's str property by

cout<<excharray;
Echo
  • 75
  • 1
  • 1
  • 7
  • 1
    overload operator `<<` – Yu Hao Aug 11 '13 at 13:45
  • 2
    Remember to point `str` to the memory of the enemy before calling `strcpy`... – 6502 Aug 11 '13 at 13:46
  • 2
    Don't you need to allocate memory for `str`? You would be better off using an `std::string`. – juanchopanza Aug 11 '13 at 13:59
  • you can also use casting operator to cast to const char *, and output directly. – SwiftMango Aug 11 '13 at 14:37
  • NO NO, really not, I will only use the ex_char by pointer, and it dont have much opportunity to change its size, if it really need to change its size, it is the time for me to start a brand new ex_char's string – Echo Aug 11 '13 at 16:59

1 Answers1

2

Assuming that you have finished the functionality correctly(in your exmaple code, you didn't allocate memory for str), overload the operator <<, so that it can be used like cout<<excharray;

ostream &operator<<(ostream &os, const ex_char &my_string)
{
    os << my_string.str;
    return os;
}

Since you need cout to access some of your class's private elements, you also need to add the operator to friend.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294