gpt4 book ai didi

c++ - 复制构造函数没有调用,为什么?

转载 作者:行者123 更新时间:2023-11-30 03:01:16 26 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Why copy constructor is not called in this case?

我有以下代码:

#include <iostream>
#include <new>

using namespace std;

class test {
int *p;
public:
test operator=(test a);
test() {
p = new int [2];
cout <<"Default Constructor was done here." << "\n";
}

test(const test &a) {
p = new int [2];
this->p[0] = a.p[0];
this->p[1] = a.p[1];
cout << "Copy Constructor was done here." << "\n";
}

~test() {
delete p;
cout << "Destructor was done here." << "\n";
}
int set (int a, int b) {
p[0] = a;
p[1] = b;
return 1;
}

int show () {
cout << p[0] << " " << p[1] << "\n";
return 2;
}
};

test test::operator=(test a) {
p[0] = a.p[0];
p[1] = a.p[1];
cout << "Operator = was done here" << "\n";
return *this;
}

test f(test x) {
x.set(100, 100);
return x;
}

int main () {
test first;
test second;
first.set(12, 12);

//f(first);
//second = first;
second = f(first);


first.show();
second.show();

getchar ();
return 0;
}

Copy Constructor 只调用了 3 次?为什么?如果我理解,我们制作了四份拷贝(我们将对象发送到 func,func 返回值,我们将对象发送到 operator=,operator= 返回值)。

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