【问题标题】:Can someone explain this debug ques?有人可以解释这个调试问题吗?
【发布时间】:2015-11-18 07:02:37
【问题描述】:

我在调试练习测试中遇到了这个问题。请帮助我理解输出。

foo(a) 产生:“复制”和“foo 调用”,而 bar(a) 产生:“bar 调用”。谁能解释这两个调用的工作原理?

#include <stdio.h>
#include <stdlib.h>

class A
{
public:
    A() : val_(0) {}
    ~A () {}
    A(const A& c)
    {
        if(&c != this)
        {
            printf("Copying \n");
            this->val_ = c.val_;
        }
    }
    void SetVal(int v) {this->val_ = v;}
    int GetVal() {return (this->val_);}

private:
    int val_;
};

static void foo(A a)
{
    printf("foo called \n");
    a.SetVal(18);
}
static void bar(A& a)
{
    printf("bar called \n");
    a.SetVal(22);
}

int main(int, char**)
{
    A a;
    a.SetVal(99);    
    foo(a);    
    bar(a);
    return 0;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    签名void foo(A a)通过值传递A,因此它将复制输入参数,然后在函数中使用它。

    void bar(A&amp; a) 传递对输入参数的引用,因此您调用函数时使用的参数将在函数中使用。

    编辑:要获得更完整的解释,此链接可能会有所帮助:http://courses.washington.edu/css342/zander/css332/passby.html

    【讨论】:

      【解决方案2】:
      void foo(A a) uses "pass by value". Which invokes copy constructor. Hence printing: "Copying" and then "foo called"
      
      void bar(A& a)uses "pass by reference". Which does not invoke copy constructor. Hence printing only: "bar called"
      

      difference

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-26
        • 2020-05-02
        • 2013-01-09
        • 2012-04-19
        相关资源
        最近更新 更多