venkysmarty
venkysmarty

Reputation: 11441

defining output operator << in C++ for user defined type

struct myVals {
        int val1;
        int val2;
    };

    I have static functions

static myVals GetMyVals(void)
{
    // Do some calcaulation.


    myVals  val;
        val.val1 = < calculatoin done in previous value is assigned here>;
        val.val2 = < calculatoin done in previous value is assigned here>;

    return val;
}


bool static GetStringFromMyVals( const myVals& val, char*  pBuffer, int sizeOfBuffer, int   count)
{
    // Do some calcuation.
       char cVal[25];

    // use some calucations and logic to convert val to string and store to cVal;

    strncpy(pBuffer, cVal, count);

    return true;
}

My requirement here is that i should have above two functions to be called in order and print the string of "myvals" using C++ output operator (<<). How can we achieve this? Does i require new class to wrap this up. Any inputs are help ful. Thanks

pseudocode:
    operator << () { // operator << is not declared completely
        char abc[30];
        myvals var1 = GetMyVald();
        GetStringFromMyVals(var1, abc, 30, 30);
        // print the string here.
    }

Upvotes: 2

Views: 2437

Answers (1)

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76848

The signature for this operator is as follows:

std::ostream & operator<<(std::ostream & stream, const myVals & item);

An implementation could look like this:

std::ostream & operator<<(std::ostream & stream, const myVals & item) {
    stream << item.val1 << " - " << item.val2;
    return stream;
}

Upvotes: 6

Related Questions