此文编写参考狄泰软件学院唐佐林老师的视频课程,如有错误之处,欢迎指正。
一、构造函数的由来
1、对象成员初始值问题
从程序设计的角度来看,对象本质上就是一个变量,因此有如下结论:
----在栈上创建对象时,成员变量的初始值为随机值
----在堆空间上创建对象时,成员变量的初始值为随机值
----在静态存储区创建对象时,成员变量的初始值为0,既全局变量和用static声明过的变量。
#include<iostream>
using namespace std;
class Test
{
private:
int i;
int j;
public:
int getI() {
return i; }
int getJ() {
return j; }
};
Test gt;//全局对象,在静态存储区
int main()
{
cout<<"gt.i ="<<gt.getI()<<endl;
cout<<"gt.j ="<<gt.getJ()<<endl;
Test t1; //在栈空间
cout<<"t1.i ="<<t1.getI()<<endl;
cout<<"t1.j ="<<t1.getJ()<<endl;
Test* pt = new Test; //在堆空间
cout<<"pt->i = "<<pt->getI()<<endl;
cout<<"pt->j = "<<pt->getJ()<<endl;
delete pt;
return 0;
}
#include<iostream>
using namespace std;
class Test
{
private:
int i;
int j;
public:
int getI() {
return i; }
int getJ() {
return j; }
void initialize()
{
i = 1;
j = 2;
}
};
Test gt;
int main()
{
gt.initialize();
cout<<"gt.i ="<<gt.getI()<<endl;
cout<<"gt.j ="<<gt.getJ()<<endl;
Test t1;
t1.initialize();
cout