将对象传递给函数并不是导致构造函数调用

passing an object to a function is not resulting into a constructor call

本文关键字:函数调用 并不是 函数 对象      更新时间:2023-10-16

当我在以下代码中调用f1时,不应该打电话给构造函数吗?我看到"这个"指针在对象b(param到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 constructorn");
}