今天看到一片文章,写的太好了,让我醍醐灌顶,所以我把这篇文章的一些内容总结下来,并附上我自己的一些理解和感悟
文章链接:
当我们定义一个类之后,编译器会自动为该类定义默认构造函数
,当我们显示重载其他构造函数时(包括拷贝构造函数),编译器遍不会再生成默认构造函数了
使用默认构造函数的例子
class Test
{
public:
int a;
int b;
int c;
};
int main()
{
Test t1;
Test t2{1,2,3};
Test t3={1,2,3};
Test t4=Test{1,2,3}; //这种构造方式调用的是构造函数而非拷贝构造
Test *t5 = new Test; //这种方式构造也是调用构造函数而非拷贝构造
Test *t6 = new Test();
Test *t7 = new Test{1,2,3};
}
Test t1就是调用类的默认构造函数,并且成员的值均为随机
Test t2{1,2,3}调用的也是类的默认构造函数,成员的值是被设置好的.
误区
使用默认构造函数时,不能这样创建对象
Test t1();
这会让编译器认为,你声明了一个返回类型为Test,函数名为t1的无参函数.
当我们去显示的定义任何构造函数时,编译器都会把默认构造函数隐藏掉
无参构造函数
class Test
{
public:
int a;
int b;
int c;
Test()
{
cout<<"调用无参构造函数“<全缺省的构造函数
class Test
{
public:
int a;
int b;
int c;
Test(int a=10)
{
this->a=a;
cout<<"调用了全缺省构造函数"<使用构造函数的简单例子
class Test
{
public:
int a;
int b;
int c;
Test(int a,int b,int c)
{
this->a=a;
this->b=b;
this->c=c;
cout<<"调用了构造函数"<在定义完一个类之后,编译器也会自动为这个类生成隐式的默认构造函数,这个默认构造函数采用的是浅拷贝的方式,深拷贝浅拷贝概念可以参照之前的文章,当我们的类中有指针成员时,我们就需要重载拷贝构造函数,实现深拷贝.当我们显示的重载拷贝构造函数之后,原本的默认构造函数与默认拷贝构造函数都会被隐藏.
使用默认拷贝构造函数的例子:
class Test
{
public:
int a;
int b;
int c;
Test(int a,int b,int c)
{
this->a=a;
this->b=b;
this->c=c;
}
} ;
int main()
{
Test t1(1,2,3);//调用构造函数
Test t2=t1; //调用了默认的拷贝构造函数
Test t3(t1);
Test t4{t1};
Test t5={t1};
Test t6=Test(t1);
Test t7=Test{t1};
}
#include
using namespace std;
class Test
{
public:
int a;
int b;
int c;
Test(){
cout<<"调用了无参构造函数”<a=a;
this->b=b;
this->c=c;
cout<<"调用了构造函数"<