在C++中为用户定义的类型定义输出operator <<

ven*_*rty 1 c++

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;
}
Run Code Online (Sandbox Code Playgroud)

我的要求是,我应该按顺序调用上面两个函数,并使用C++输出运算符(<<)打印"myvals"字符串.我们怎样才能做到这一点?我是否需要新的课程来包装它.任何输入都有帮助.谢谢

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

Bjö*_*lex 5

该运营商的签名如下:

std::ostream & operator<<(std::ostream & stream, const myVals & item);
Run Code Online (Sandbox Code Playgroud)

实现可能如下所示:

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

  • 你怎么能把它变成一个普通的成员函数?它必须是 std::ostream 的成员!`friend` 应该可以工作,但我不建议这样做 - 如果可能,应该首选非友元、非成员函数(请参阅 Effective C++ 和 C++ Coding Standards) (2认同)