gpt4 book ai didi

c++ - 赋值操作和对象传递期间的构造函数调用

转载 作者:行者123 更新时间:2023-11-30 01:22:55 25 4
gpt4 key购买 nike

我对按引用传递对象和按值传递给特定类的函数之间的区别感到困惑。如果我按值传递对象,我知道默认复制构造函数会逐个成员地复制对象以供在给定函数中使用。但是,如果我将对象作为常量引用传递给需要深度复制的类,是否仍会调用复制构造函数?说我有一个函数

     void debug(const MyClass& object1); 

传递 object1 会调用复制构造函数吗?或者是对象直接传递给函数而不进行复制?还有一个问题 - 如果我有一个名为 Fraction 的类 -

     Fraction A(1,2); // 1 is this numerator, 2 the denominator

A = Fraction(2,3);

上述行是否调用了默认构造函数来创建一个临时对象 Fraction(2,3) 然后是赋值运算符?

谢谢。

最佳答案

传递 object1 会调用复制构造函数吗?

不,它不会调用复制构造函数,因为它是通过引用传递的这种情况下不复制

A = Fraction(2,3);

是的,它将调用带两个参数的构造函数(如果两个参数都有默认值,则调用默认构造函数),然后调用复制赋值运算符。

您可以看到以下代码的输出:

 #include <iostream>
using namespace std;
class Fraction
{
public:
int denom;
int nominator;
Fraction(int d , int n ):denom(d), nominator(n)
{
cout << "call non-copy constructor" <<endl;
}

Fraction(const Fraction& rhs)
{
cout << "call copy constructor" <<endl;
denom = rhs.denom;
nominator = rhs.nominator;
}

const Fraction& operator=(const Fraction& rhs)
{
cout << "call copy assignment operator" << endl;
if (this == &rhs)
{
return *this;
}

denom = rhs.denom;
nominator = rhs.nominator;
return *this;
}
};

void debug(const Fraction& obj)
{
cout << "this is debug: pass by reference " <<endl;
}

void debugPassByValue(Fraction obj)
{
cout << "this is debug: pass by value" <<endl;
}

int main()
{
Fraction A(1,2);
cout << "--------------" <<endl;
debug(A);
cout << "--------------" <<endl;
A = Fraction(2,3);
cout << "--------------" <<endl;
debugPassByValue(A);
cout << "--------------" <<endl;
cin.get();
return 0;

您将看到以下输出:

call non-copy constructor  //Fraction A(1,2);
--------------
this is debug: pass by reference //debug(A);
--------------
call non-copy constructor //A = Fraction(2,3);---> construct temporary object
call copy assignment operator //A = Fraction(2,3);
--------------
call copy constructor //debugPassByValue(A);
this is debug: pass by value
--------------

现在你对什么叫做更清楚了。

关于c++ - 赋值操作和对象传递期间的构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15606518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com