C++ execution order in method chaining

前端 未结 4 446
猫巷女王i
猫巷女王i 2021-01-30 12:32

The output of this program:

#include  
class c1
{   
  public:
    c1& meth1(int* ar) {
      std::cout << \"method 1\" << std::e         


        
4条回答
  •  失恋的感觉
    2021-01-30 12:58

    I think when compiling ,before the funtions meth1 and meth2 are really called, the paramaters have been passed to them. I mean when you use "c.meth1(&nu).meth2(nu);" the value nu = 0 have been passed to meth2, so it doesn't matter wether "nu" is changed latter.

    you can try this:

    #include  
    class c1
    {
    public:
        c1& meth1(int* ar) {
            std::cout << "method 1" << std::endl;
            *ar = 1;
            return *this;
        }
        void meth2(int* ar)
        {
            std::cout << "method 2:" << *ar << std::endl;
        }
    };
    
    int main()
    {
        c1 c;
        int nu = 0;
        c.meth1(&nu).meth2(&nu);
        getchar();
    }
    

    it will get the answer you want

提交回复
热议问题