printf and custom class

后端 未结 4 1718
情深已故
情深已故 2020-12-21 16:31

I have my own class that represents a custom string class. I\'m using VS2012RC. I have overloaded some operators of my class CustomString.

Here\'s some code:

<
4条回答
  •  生来不讨喜
    2020-12-21 16:51

    You can't (at least not in a portable way). printf looks at the object passed as parameter and treats it as a %s, which is a char array. You run into undefined behavior. Also, the parameters passed to printf are, sort of say, type-less.

    Why printf(str) is ok?

    Because the first parameter is types, and is a const char*. The implicit cast is made via your operator. The rest of the parameters don't behave the same.

    I'd use cout instead, and overload operator << (ostream&, const CustomString&).

    Don't do this:

    I said you can't, in a portable way. For a class like

    class CustomString
    {
       char* str;
       //...
    };
    

    that might work, because of how classes are represented in memory. But, again, it's still undefined behavior.

提交回复
热议问题