2016-09-17 130 views
2

我尝试下面的程序:为什么在通过值传递给函数并将值传递给另一个构造函数时,构造函数的调用有什么区别?

#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()
顺便说一句,当我使用初始化列表。

回答

2

我很奇怪,为什么当我把它传递给MyClass的构造

它无关,与这里路过参数的默认构造函数被调用。作为成员变量,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 
    } 
}; 

您可以指定variable将通过成员初始化程序列表中初始化,就像

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 
    } 
}; 

默认构造函数将不会被调用这种情况。

+1

[迂回]'变量'不是从'a'复制初始化,它是直接初始化的。 – Barry

0

对参数(MyClass构造函数和fun的参数)以及您发布的日志报告这两个参数都会调用复制构造函数。
事实上,你有下面这行两次:

称为

默认的构造函数被调用的数据成员variable类型的拷贝构造函数,因为它是不明确的初始化。
同样的情况,如果您使用的初始化列表如下:

MyClass(Type a): variable{} { 
    //... 
} 

其实,如果你没有任何初始化列表variable被默认初始化,所以没有理由期待一个不同的日志。

相关问题