gpt4 book ai didi

c++ - 复制构造函数 C++

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

抱歉,我正在努力掌握复制构造函数,我想知道为什么仅当我按值“op.return_Value(op)< 调用函数中的对象时才调用复制构造函数

class operation{
public:
int add(int x,int y){
*total=x+y;
return (*total);
}

operation(){
cout<<"This is the constructor"<<endl;
total=new int;
}
operation(const operation &op){
cout<<"This is the copy of the start"<<endl;
total=new int;
*total=*op.total;
}

~operation(){
cout<<"This is the end";
delete total;
}

int *total;

int return_Value(operation op){
return *total;
}

};

class child_operation:operation{

public:

int sub(int x,int y){
*total=x-y;
return(*total);
}

};



int main()
{
operation op;
child_operation op1;

cout<<op.add(5,6)<<endl<<op1.sub(6,5)<<endl;
cout<<op.return_Value(op)<<endl;
}

复制构造函数基本上以哪些方式被调用?

最佳答案

它非常简单,并在标准 (12.8.1) 中明确说明:

A class object can be copied in two ways, by initialization (including for function argument passing and for function value return) and by assignment. Conceptually, these two operations are implemented by a copy constructor and copy assignment operator.

因此,如果您要显式或隐式地初始化一个新对象(例如,通过复制将一个对象传递给函数,这是您的情况,或者从函数返回一个对象),复制构造函数被调用:

MyClass a = b;//initialization, copy constructor is called
//or
void foo(MyClass a){}//a is passed by value, a copy will be made, and copy constructor will be called
//or
MyClass foo()
{
MyClass result;
return result;//a copy of result will be returned, and copy constructor will be called
}

相反,如果您要进行赋值,则会调用 operator=,例如

MyClass x;
MyClass y;
y = x;//assignmanet

关于c++ - 复制构造函数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32094881/

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