gpt4 book ai didi

c++ - 为什么按值传递给函数和按值传递给另一个构造函数时,构造函数的调用会有所不同?

转载 作者:搜寻专家 更新时间:2023-10-31 02:14:45 25 4
gpt4 key购买 nike

我正在尝试以下程序:

#include <iostream>
using namespace std;
class Type{
int i;
public:
Type() {cout << "type constructor "<<endl;}
Type (const Type &) { cout << "type copy constructor called" << endl;}
};

class MyClass {
Type variable;
public:
MyClass(Type a) {
cout << "inside MyClass constructor "<<endl;
variable = a;
}
};
void fun (Type){
return;
}

int main (){
Type t;
cout <<"t created"<<endl;
MyClass tmp = MyClass(t);
cout<<"calling fun"<<endl;
fun(t);
}

这个的输出是:

type constructor 
t created
type copy constructor called
type constructor
inside MyClass constructor
calling fun
type copy constructor called

我想知道为什么当我将它传递给 MyClass 构造函数时调用默认构造函数,为什么当我将它传递给 fun() 时调用复制构造函数?
顺便说一句,当我使用初始化列表时也会发生同样的情况。

最佳答案

I am wondering why default constructor is called when I pass it to MyClass constructor

此处与传参无关。 variable作为成员变量,首先会默认构造。

class MyClass {
Type variable;
public:
MyClass(Type a) { // variable will be default constructed at first, since it's not initialized via member initializer list
cout << "inside MyClass constructor "<<endl;
variable = a; // then variable is assgined via assignment operator
}
};

您可以指定成员初始化器列表如何初始化变量,例如

class MyClass {
Type variable;
public:
MyClass(Type a) : variable(a) { // variable will be direct initialized via copy constructor
cout << "inside MyClass constructor "<<endl;
// variable = a; // no need for assignment
}
};

在这种情况下不会调用默认构造函数。

关于c++ - 为什么按值传递给函数和按值传递给另一个构造函数时,构造函数的调用会有所不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39548274/

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