Calling base class insert operator when deriving from ofstream

Started by
2 comments, last by BerwynIrish 16 years, 3 months ago
I'm sub-classing from ofstream and have over-ridden the insert operator. Within my class's insert operator I eventually call ofstream::operator<< to write to the file. It works for the integer version, but I can't get it to work for character arrays or for single characters. For character arrays, a hex value is written which I'm reasonably sure is the address of the pointer, and for single chars, the integer value of the char is written to the file.

class MyClass: public ofstream
{
    public:
    MyClass     &operator<<(const char*);

};

MyClass &MyClass::operator<<(const char *string)
{
    ofstream::operator<<(' '); 
    ofstream::operator<<(string);
    ofstream::operator<<(1000);
    return *this;
}

int main(void)
{
    MyClass file;
    file.open("test.txt");
    file << "test";
    file.close();
    return 0;
}
test.txt contains: 320x4430091000 How do I modify this to get single characters rather than their integer value and strings rather than the pointer value?
Advertisement
Quote:Original post by BerwynIrish
but I can't get it to work for character arrays

Problem #1: operator<< for (const char*) is a non-member function. Yours probably should be to:

MyClass& operator<<( MyClass& myos, const char* string ) {    ...    ((ofstream&) myos) << string;    ...    return *this;}


Quote:or for single characters.

Problem #2: ostreams treat "char" as an integer type (because it is). Convert single characters to strings:

MyClass& operator<<( MyClass& myos, const char* string ) {    ((ofstream&) myos) << " ";    char str[] = { some_char_variable, '\0' };    ((ofstream&) myos) << str;    ...    return *this;}


Quote:which I'm reasonably sure is the address of the pointer

You are correct here. It's using ostream::operator<<( void* ) which is a member function. Don't you just love C++?
I am curious as to why you are doing this. However, this works for me:
MyClass &MyClass::operator<<(const char *string){    static_cast<std::ofstream&>(*this) << ' ';    static_cast<std::ofstream&>(*this) << string;    static_cast<std::ofstream&>(*this) << 1000;    return *this;}


[edit: I agree, making your function a non member would be better too]
Thanks guys, I got it working.

Quote:Original post by rip-off
I am curious as to why you are doing this.

It's for a log file. I want the output of each logged function to be indented relative to its position in the call stack. So at the beginning of each logged function I'd do something like "mystream << foo;" to add another tab to the indention of any following output and then put "mystream << bar;" at the end of the function to tell the stream to subtract a tab.

This topic is closed to new replies.

Advertisement