/*
1)当类中没有定义任何一个构造函数时,c++编译器会提供默认无参构造函数和默认拷贝构造函数
2)当类中定义了拷贝构造函数时,c++编译器不会提供无参数构造函数
3) 当类中定义了任意的非拷贝构造函数(即:当类中提供了有参构造函数或无参构造函数),
c++编译器不会提供默认无参构造函数
4 )默认拷贝构造函数成员变量简单赋值
总结:只要你写了构造函数,那么你必须用。
*/
第一种情况
#if 1
class Test
{
public:
//第一种情况 不写任何函数,编译通过,使用默认的构造函数
void printT()
{
cout << "a:" << a << "b: " << b << endl;
}
protected:
private:
int a;
int b;
};
void test()
{
Test t1; //调用无参构造函数
cout << "hello..." << endl;
}
#endif
第2种情况
#if 1
class Test
{
//第2种情况 编译通过
Test()
{
printf("默认的构造函数\n");
}
void printT()
{
cout << "a:" << a << "b: " << b << endl;
}
protected:
private:
int a;
int b;
};
void test()
{
Test t1; //调用无参构造函数
cout << "hello..." << endl;
}
#endif
第3种情况
#if 1
class Test
{
public:
//第3种情况 编译不通过
Test(int _a, int _b)//会
{
;
}
void printT()
{
cout << "a:" << a << "b: " << b << endl;
}
protected:
private:
int a;
int b;
};
void test()
{
Test t1; //调用无参构造函数
cout << "hello..." << endl;
}
#endif
结果:
第4种情况
当类中定义了拷贝构造函数时,c++编译器不会提供无参数构造函数
#if 1
class Test
{
public:
//第4种情况 编译不通过
Test(const Test& obj) //copy构造函数 作用: 用一个对象初始化另外一个对象
{
a = obj.a + 100;
b = obj.b + 100;
}
void printT()
{
cout << "a:" << a << "b: " << b << endl;
}
protected:
private:
int a;
int b;
};
void test()
{
Test t1; //调用无参构造函数
cout << "hello..." << endl;
}
#endif