方法链中的C ++执行顺序 [英] C++ execution order in method chaining

查看:76
本文介绍了方法链中的C ++执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序的输出:

#include <iostream> 
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);
}

是:

method 1
method 2:0

为什么meth2()开始时nu不是1?

推荐答案

因为未指定评估顺序.

在调用meth1之前,您已经看到main中的nu被评估为0.这是链接的问题.我建议不要这样做.

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);
}

这篇关于方法链中的C ++执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆