初始化与构造函数

1  c++的内置类型只有int ,double ,long,char等,并不包括string,string是stl定义的一个类

2  在没有任何显式的初始化时,编译器会执行默认初始化:对于类类型,由类自己定义默认初始化时的操作,对于内置类型,内置类型的数组,或者指针,如果是全局变量或者静态局部变量,则初始化为0,如果是自动变量,则不会进行初始化,其值将是未定义的

3  对于类类型

如果定义了默认构造函数,那么在需要默认初始化的时候就只会执行该默认构造函数的内容,对于默认构造函数没有初始化的成员,按照声明顺序进行默认初始化。

如果没有定义默认构造函数,但是定义了其他的构造函数,则这个类不允许默认初始化,在进行默认初始化时会报错

如果没有定义任何构造函数,则编译器会定义一个合成的默认构造函数,对每个成员变量进行默认初始化

4  在使用=初始化的时候,即classA A = C 时,如果C的类型是classA,则直接调用拷贝构造函数,否则“尝试”执行隐式转换,然后再用拷贝构造,如果可行,编译器可以选择将代码变成

classA A(C)处理。

5   类的拷贝,赋值与销毁

c++11标准有5种操作可以控制类的拷贝操作:拷贝构造函数,拷贝赋值运算符,析构函数,移动构造函数,移动赋值运算符

include <iostream> 

#include <string>

 

using namespace std;

 

class test{

public:

    string str;

    int num;

    static int count;

    test() : str(""), num(0) {++count; cout<<"默认初始化"<<"这是第 "<<count<<" 个对象"<<endl;}

    test(const test& t) : str(t.str), num(t.num) {++count; cout<<"拷贝初始化"<<"这是第 "<<count<<" 个对象"<<endl;}

    test(string s, int n) : str(s), num(n) {++count; cout<<"普通匹配初始"<<"这是第 "<<count<<" 个对象"<<endl;}

    test(int s) :str(""), num(s) {++count; cout<<"转换初始化"<<"这是第 "<<count<<" 个对象"<<endl;}

    test(string s): str(s), num(0) {++count; cout<<"转换初始化"<<"这是第 "<<count<<" 个对象"<<endl;}

    ~test(){cout<<"销毁了第 "<<count--<<" 个对象"<<endl;}

};

int test::count = 0;

 

test fun(test s){ 

    return s;

}

int main(){

    string s = "sts";

    int n = 0;

    test t1, t2(s), t3 = s, t4 = t1; 

    t1 = s;

    t2 = n;

    fun(s);

    return 0;

}

1,某些情况编译器可以略过对拷贝构造函数的调用,比如Foo f1 = s;编译器可以优化成Foo f1(s)。但是这个过程需要保证copy constructor 跟convert constructor都是可用的

2,隐式转换的过程为调用转换构造函数构造一个  临时变量  用于计算,该临时变量为常量

 

posted on 2014-11-27 18:39  远近闻名的学渣  阅读(258)  评论(0)    收藏  举报

导航