C++ 将对象传递给函数不会导致构造函数调用

C++ 将对象传递给函数不会导致构造函数调用,c++,function,for-loop,constructor,C++,Function,For Loop,Constructor,当我在下面的代码中调用f1时,是否应该调用构造函数? 我看到对象b中的“this”指针不同(参数为f1),这意味着创建了一个新对象,但我在构造函数中没有看到b的打印。 但有人在召唤毁灭者,有人能解释吗 class A { int k ; public: A(int i) { k=i; printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this); } ~A() {

当我在下面的代码中调用f1时,是否应该调用构造函数? 我看到对象b中的“this”指针不同(参数为f1),这意味着创建了一个新对象,但我在构造函数中没有看到b的打印。 但有人在召唤毁灭者,有人能解释吗

class A
{
    int k ;
public:
    A(int i)
    {
        k=i;
        printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this);
    }
    ~A()
    {
        printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this);
    }
    void A_fn()
    {
        printf("%d inside [%s]ptr[%p]\n",k,__FUNCTION__,this);
    }
};
void f1(A b)
{
    b.A_fn();
}
int _tmain(int argc, _TCHAR* argv[])
{
    A a(10);
    f1(a);
    return 0;
}
vc++2012中显示的输出:

10 inside [A::A]ptr[00B3FBD0]

10 inside [A::A_fn]ptr[00B3FAEC]

10 inside [A::~A]ptr[00B3FAEC]

10 inside [A::~A]ptr[00B3FBD0]

Press any key to continue . . .

因为当您按值传递对象时,对象被复制,因此复制构造函数将被调用。

因为当您按值传递对象时,对象被复制,因此复制构造函数将被调用。

如前所述,您需要将复制构造函数添加到类a中。它应该是这样的:

A(const A&)
{
    printf("Inside copy constructor\n");
}

如前所述,您需要向类a添加一个副本构造函数。它应该是这样的:

A(const A&)
{
    printf("Inside copy constructor\n");
}

在复制构造函数中添加注释并选中…在复制构造函数中添加注释并选中。。。