C++ execution order in method chaining

前端 未结 4 575
猫巷女王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:52

    Because evaluation order is unspecified.

    You are seeing nu in main being evaluated to 0 before even meth1 is called. This is the problem with chaining. I advise not doing it.

    Just make a nice, simple, clear, easy-to-read, easy-to-understand program:

    int main()
    {
      c1 c;
      int nu = 0;
      c.meth1(&nu);
      c.meth2(nu);
    }
    

提交回复
热议问题