构造函数是一种特殊的函数,它和类同名但是不返回任何值,可以在类声明中定义也可以在类声明之外定义
class Human { public: Human() { //constructor code here } }; //在类声明之外定义 class Human { public: Human();//constructor declaration }; //constructor implementation (definition) Human ::Human() { //constructor code here } //::被称作作用域解析运算符,例如:Human::dateOfBirth指的是在Human类 //中声明的变量dateOfBirth,而::dateOfBirth表示全局作用域中的变量dateOfBirth
//使用构造函数初始化类成员变量 #include<iostream> #include<string> using namespace std; class Human//类 { private://私有 string name; int age; public: Human()//constructor { age = 1; cout<<"constructed an instance of class Human"<<endl; } void SetName (string humansName) { name = humansName; } void SetAge(int humansAge) { age = humansAge; } void IntroduceSelf() { cout<<"I am"+name<<"and am"; cout<<age<<"years old"<<endl; } }; int mian() { Human firstWoman; firstWoman.SetName("Eve"); firstWoman.SetAge(28); firstWoman.IntroduceSelf(); }
//重载构造函数