您的位置:首页 > 编程语言 > C语言/C++

构造函数

2016-03-02 17:28 405 查看
1、类内部没有任何构造函数时

class stu{
private :
int id;
string name;
public:
};
int main()
{
stu b;
return 0;
}


此时,调用编译器调用默认的无参构造函数,此构造函数什么也不做。


2、类内部有无参数的构造函数

class stu{
private :
int id;
string name;
public:

stu()
{
id=1;
name="jack";
cout<<"this construc function is used"<<endl;
}
void show()
{
cout<<id<<" "<<name<<endl;
}
};
int main()
{
stu b;
b.show();
return 0;
}


此时调用类内部的无参数构造函数


3、类内部有多个构造函数时

class stu{
private :
int id;
string name;
public:

stu(int a,string b="jack")
{
id=a;
name=b;
cout<<"finish"<<endl;
}

stu()
{
id=1;
name="jack";
cout<<"this construct function is used"<<endl;
}
void show()
{
cout<<id<<" "<<name<<endl;
}
};
int main()
{
stu a(1);
a.show();
stu b;
b.show();
return 0;
}


执行结果:

1 jack
this construct function is used
1 jack


class stu{
private :
int id;
string name;
public:

stu(int a,string b="jack")
{
id=a;
name=b;
cout<<"finish"<<endl;
}

void show()
{
cout<<id<<" "<<name<<endl;
}
};
int main()
{
stu b;
b.show();
return 0;
}


执行结果:

[Error] no matching function for call to 'stu::stu()'


此时,说明如果类内部有构造函数,那么在调用构造函数时,编译器就会去匹配类内部构造函数,看是否可以匹配上。

此程序,若添加无参构造函数则可以正确运行;或者将构造函数改为stu(int a=1,string b=”jack”)。

4、构造函数用在数组中

class test{
test(int n,int m){}//1
test(int n){}//2
test(){}//3
};


test array1[3]={1,test(1,2)};
第一个对象初始化调用构造函数1,第二对象初始化调用构造函数2,第三个对象初始化调用无参构造函数3;


test array2[3]={test(1,2),test(1,2),1};
//test array2[3],生成三个test对象,三个元素分别用2,2,1初始化


test * pArray[3]={new test(4),new test(1,2)}
pArray是指针数组,每一元素都是指向test对象的指针;
test * pArray[3]前半句并不会生成test对象,只是构建了三个指针。
第一个指针指向了new test(4)生成的对象,第二个指针指向new test(1,2)生成的对象,第三个指针为空。


NOTE:

构造函数并不负责分配对象的存储空间,只是在对象创建之后,即存储空间分配之后,对对象的属性值进行初始化。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 构造函数 初始化