FtpClient::FtpClient(): m_purl_handle(NULL)
{
m_nConCount = 4;
m_nIsLoginCount = 4;
}
在没有默认构造函数的时候,如果一个类对象是另一个类的数据成员,那么这个初始化这个数据成员,就应该放到初始化列表里面,这样在创建对象的时候就可以带参数。
//初始化列表初始化成员为结构体或者类的成员变量
CAnimal::CAnimal(CInfo info, QString des):m_info(info)
{
m_description = des;
}
//传类对象的数据成员的参数到构造函数
/*CAnimal::CAnimal(CInfo info, QString des
)
{
m_info = info;
m_description = des;
}*/
==================初始化列表和构造函数===========
1. ====内部数据类型====
class Animal
{
public:
Animal(int age, qstring name){
m_age = age;
m_name = name; // 构造函数内部赋值方式
}
private:
int m_age;
qstring m_name;
};
class Animal
{
public:
Animal(int age, qstring name) : m_age(age), m_name(name)
{
} // 构造函数外面初始化列表方式
private:
int m_age;
qstring m_name;
};
2. =======无默认构造函数的继承关系中=======
class Animal
{
public:
Animal(int age, qstring name):
m_age(age),m_name(name) // 初始化列表
{
}
private :
int m_age;
qstringf m_name;
};
---------------------------------------
class Dog : public Animal
{
public:
Dog(int age, qstring mame , int type); // error 父类Animal无合适构造函数
{
}
private:
int m_type;
};
因为子类Dog初始化之前要进行父类Animal的初始化,但是根据Dog的构造函数,没有给父类差到你参数,使用了父类Animal的无参构造函数。而父类Animal提供了有参的构造函数,这样编译器就不会给Animal提供一个默认的无参数的构造函数了。
在利用初始化列表进行创建子类对象时候(此时需要传进一个父类临时对象,采用CLASS("父类构造函数需要传进的参数")的方式进行父类的初始化,因为父类初始化要优先于子类对象。)如果不用临时对象,那么需要在子类构造函数外部同时也是初始化列表的外部创建一个临时父类对象,然后传入到子类对象的构造函数中进行子类对象的创建。两种方式只是写法不同,实际都是创建一个临时父类对象(可以传参数的那种),之后构建子类对象。只是一个在构造函数内创建这个临时对象,一个在构造函数外部创建这个父类临时对象。
=======================类中的const常量========
类中的const常量必须只能在初始化列表中初始化,不能使用赋值的方式进行初始化。
class Dog : public Animal
{
Animal (int age, qstring name) :
m_age (age), m_name(name)
legsNumber(4);
{
// m_legsNumber(4); /// ERROR 不能在构造函数内部赋值cosnt类型变量,只能在初始化列表中进行const变量的初始化操作。
}
private:
int m_age;
qstring m_name;
int const m_legNumber;
};
==========================包含有自定义数据类型(类)对象的初始化==============
class Food
{
public:
Food(int type = 10)
{
m_tyupe = 10;
}
Food (Food &other)
{
m_type = other.m_type;
}
Food & opearator = (Food &other)
{
m_type = other.m_type;
return *this;
}
private:
int m_type;
};
(1)构造函数赋值方式 初始化成员对象m_food
class Dog :public Animal
{
Dog(Food &food)
{
m_food = food;
}
private:
Food m_food;
};
// 使用方法:
Food fd;
Dog (fd); //
// 先执行构造函数 Food (int type = 10) ---> 执行 构造函数 Food &operator = (Food &other).
(2)构造函数初始化列表方式:
class Dog : public Animal
{
public:
Dog (Food &food) : m_food(food)
{
// 其他初始化参数
}
private:
Food m_food;
};
// 使用方式:
Food fd;
Dog dog(fd);//
// 执行Food (Food &other)拷贝构造函数完成初始化