创建一个对象时,只有一个构造函数会被调用,根据是否提供参数来选择使用有参或默认构造函数。
1. 默认构造函数(Default Constructor)
eg: User () { }
Rules:
- 和class名称一样
- 无返回值
- 是class的public member function
- 无参数
- 如果没有自行定义任何构造函数,C++会自动生成一个默认构造函数(只要自己定义了任何一种构造函数,那么C++就不会再自动生成了)
- 默认构造函数如果有的话只能有一个,不能同时定义多个(因为都是无参的,如果有两个的话compiler不知道该调用哪个了)
可以为默认构造函数设置默认值:
//定义在User类中的默认构造函数
User () {
name = "nn";
age = 0;
Email = "not set";
}
//创建新对象
User user1; //调用默认构造函数
2. 有参构造函数(Parameterized Constructor)
Rules:
和上面基本一样,除了它是有参数的,并且有参构造函数可以同时定义多个
//定义在User类中的有参构造函数
User (string inputName, int inputAge){
name = inputName;
age = inputAge;
email = "user" + inputName + "@mail.com"; //字符串用加号连接
}
//创建对象
User user2("Tom", 27); //调用有参构造函数
3. 含有默认值的有参构造函数
以一道例题为例:Modify the function header below for the constructor function for ZooAnimal. Provide default values of "Nameless" for who, 9999 for whichCage, 101 (January 1) for weighDay, and 100 for pounds.
// ---------- the constructor function
ZooAnimal::ZooAnimal (char* who, int whichCage, int weighDay, int pounds)
{
char *name = new char[20];
strcpy (name, who);
cageNumber = whichCage;
weightDate = weighDay;
weight = pounds;
}
类声明中的构造函数头:
ZooAnimal(char* who = "Nameless", int whichCage = 9999, int weighDay = 101, int pounds = 100); // 构造函数
构造函数的实现:
// ---------- 构造函数的实现
ZooAnimal::ZooAnimal(char* who, int whichCage, int weighDay, int pounds) {
name = new char[20];
strncpy(name, who, 19);
name[19] = '\0'; // 确保字符串以null字符结尾
cageNumber = whichCage;
weightDate = weighDay;
weight = pounds;
}
通过这样的实现,当你创建一个ZooAnimal
对象时,可以选择不提供任何参数,部分参数或所有参数。例如:
ZooAnimal animal1; // 使用所有默认值
ZooAnimal animal2("Tiger"); // 使用默认的cageNumber, weightDate, 和 weight
ZooAnimal animal3("Lion", 102); // 使用默认的weightDate 和 weight
ZooAnimal animal4("Bear", 103, 202); // 使用默认的weight
ZooAnimal animal5("Elephant", 104, 203, 3000); // 使用提供的所有值
【在C++中,如果构造函数的声明中已经提供了参数的默认值,那么在函数定义中不需要再次提供默认值。默认参数值只需要在函数声明中指定一次即可,在定义中省略默认值也能正常工作。
这样做的原因是C++的默认参数机制:默认参数值只在函数声明中指定一次,以避免重复和潜在的不一致。】