一、带有参数的构造函数、
--- 构造函数可以根据需要定义参数 --- 一个类中可以存在多个重载的构造函数 --- 构造函数的重载遵循C++重载的规则class Test
{
public:
Test(int v)
{
//use v to initialize member
}
};
二、对象的定义和对象的声明不同
.对象定义 --申请对象的空间并调用构造函数
.对象声明 --告诉编译器存在这样一个对象
Test t; //定义对象并调用构造函数
int main()
{
//告诉编译器存在名为t的test对象
extern Test t;
return 0;
}
三、构造函数的自动调用
class Test
{
public:
Test(){};
Test(int v){};
}
int main()
{
Test t; //调用Test();
Test t1(1); //调用Test(int v)
Test t2 = 1; //调用Test(int v)
return 0;
}
#include四、构造函数的手工调用 ---一般情况下,构造函数在对象定义时被自动调用 ---一般特殊情况下,最要手工调用构造函数class Test { public: Test() { printf("Test()n"); } Test(int v) { printf("Test(int v)n"); } }; int main() { Test t; Test t1(1); Test t2=1; //初始化 t= t2; //赋值操作 int i(100); //初始化 printf("i = %dn",i); return 0; }
#includeclass Test { private: int m_value; public: Test() { printf("Test()n"); m_value =0 ; } Test(int v) { printf("Test(int v)n"); m_value = v; } int getValue() { return m_value; } }; int main() { Test ta[3]={Test(),Test(1),Test(2) }; //手工调用构造函数 for(int i=0 ;i<3;i++) { printf("ta[%d].getValue = %dn",i,ta[i].getValue()); } return 0; }



