Using overloaded operators on pointers

后端 未结 4 916
悲&欢浪女
悲&欢浪女 2021-02-19 15:28

I overloaded the << operator of a class. How do I have to overload the operator if I want to use it on pointers, like the following?

class A {
    std::str         


        
4条回答
  •  故里飘歌
    2021-02-19 15:37

    First off, to stick with standard conventions, your operator<< should be declared like this:

    class A {
        A& operator<<(const std::string&);
    };
    

    Now, technically, you could achiever part of what you want by implementing the following global function:

    A * operator<< ( A * a, const std::string& s ) { (*a) << s; return a; }
    

    This would allow statements such as:

    string s = "this will be printed."; aPointer << s;
    aPointer << string("this will be printed");
    

    However, you won't be able to write the following:

    aPointer << "this will not compile.";
    

    In any case, writing such an operator would be confusing, at best. You should live with the more simple syntax of

    (*aPointer) << "this will be printed.";
    

    and write code that sticks to established conventions to allow others (and yourself, in a few weeks) to read your code.

提交回复
热议问题