我尝试下面的程序:为什么在通过值传递给函数并将值传递给另一个构造函数时,构造函数的调用有什么区别?
#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()
?
顺便说一句,当我使用初始化列表。
[迂回]'变量'不是从'a'复制初始化,它是直接初始化的。 – Barry