'printf' vs. 'cout' in C++

后端 未结 16 1755
梦如初夏
梦如初夏 2020-11-22 07:04

What is the difference between printf() and cout in C++?

16条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 07:37

    With primitives, it probably doesn't matter entirely which one you use. I say where it gets usefulness is when you want to output complex objects.

    For example, if you have a class,

    #include 
    #include 
    
    using namespace std;
    
    class Something
    {
    public:
            Something(int x, int y, int z) : a(x), b(y), c(z) { }
            int a;
            int b;
            int c;
    
            friend ostream& operator<<(ostream&, const Something&);
    };
    
    ostream& operator<<(ostream& o, const Something& s)
    {
            o << s.a << ", " << s.b << ", " << s.c;
            return o;
    }
    
    int main(void)
    {
            Something s(3, 2, 1);
    
            // output with printf
            printf("%i, %i, %i\n", s.a, s.b, s.c);
    
            // output with cout
            cout << s << endl;
    
            return 0;
    }
    

    Now the above might not seem all that great, but let's suppose you have to output this in multiple places in your code. Not only that, let's say you add a field "int d." With cout, you only have to change it in once place. However, with printf, you'd have to change it in possibly a lot of places and not only that, you have to remind yourself which ones to output.

    With that said, with cout, you can reduce a lot of times spent with maintenance of your code and not only that if you re-use the object "Something" in a new application, you don't really have to worry about output.

提交回复
热议问题