内容参考于《21天学通C++》(第八版)
不去纠结C++的原理和细节,从C的角度去学习C++,再通过C++项目去加深理解
一.构造函数
1. 示例1:构造函数是可以重载
#include <iostream>
#include <string>
using namespace std;
class Human
{
private:
string name;
int age;
public:
Human() // default constructor
{
age = 0; // initialized to ensure no junk value
cout << "Default constructor: name and age not set" << endl;
}
Human(string humansName, int humansAge) // overloaded
{
name = humansName;
age = humansAge;
cout << "Overloaded constructor creates ";
cout << name << " of " << age << " years" << endl;
}
};
int main()
{
Human firstMan; // use default constructor
Human firstWoman("Eve", 20); // use overloaded constructor
}
运行结果
Default constructor: name and age not set
Overloaded constructor creates Eve of 20 years
2. 示例2:实例对象强制输入参数
直接去掉上面代码的Human()部分
Human() // default constructor
{
age = 0; // initialized to ensure no junk value
cout << "Default constructor: name and age not set" << endl;
}
那么编译就会报错
Human firstMan;没有合适的默认构造函数可用
3. 示例3:带默认值的构造函数参数
class Human
{
private:
string name;
int age;
public:
// overloaded constructor (no default constructor)
Human(string humansName, int humansAge = 25)
{
name = humansName;
age = humansAge;
cout << "Overloaded constructor creates " << name;
cout << " of age " << age << endl;
}
// ... other members
};
// 可以这样调用
Human adam("Adam"); // adam.age is assigned a default value 25
Human eve("Eve", 18); // eve.age is assigned 18 as specified
4. 示例4:包含初始化列表的构造函数
#include <iostream>
#include <string>
using namespace std;
class Human
{
private:
int age;
string name;
public:
Human(string humansName = "Adam", int humansAge = 25)
: name(humansName), age(humansAge)
{
cout << "Constructed a human called " << name;
cout << ", " << age << " years old" << endl;
}
};
int main()
{
Human adam;
Human eve("Eve", 18);
return 0;
}
运行结果
Constructed a human called Adam, 25 years old
Constructed a human called Eve, 18 years old
下面语句快捷得把输入得参数设置进了成员里面
: name(humansName), age(humansAge)