一个例子
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
int num;
string name;
};
int main()
{
Person p;
static Person w;
cout << "p: " << p.num << endl;
return 0;
}
当Person p时,C++会自动写默认的构造函数来初始化类。
这里是原先没有被清除内存里的值,这样不是很好,所以我们需要自己动手写构造函数。
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
int num;
string name;
public:
Person():num(0){}
};
int main()
{
Person p;
static Person w;
cout << "p: " << p.num << endl;
return 0;
}
说明:1,构造函数的名字和类的名字相同。
2,简单的构造函数可以像例子那样书写,Person():num(0){}(推荐)
3,构造函数可以这样写:
Person()
{
num = 0;
}
拓展
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
int num;
string name;
};
Person q;
int main()
{
Person p;
static Person w;
cout << "p: " << p.num << endl;
cout << "q: " << q.num << endl;
cout << "w: " << w.num << endl;
return 0;
}
当类变量是全局变量,以及static的时候,C++会自动把num初始化为0.