`#include"stdafx.h"
#include<string>
#include<iostream>
using namespace std;
class person
{
public:
person()
{
cout<<"打印构造函数"<<endl;
}
};
int main()
{
person p;
}
此代码是为了演示构造函数在创建对象时系统 *自动* 调用的证明
编译结果
*******打印构造函数
********请按任意键继续. . .
析构函数:
对象在销毁前,会自动调用析构函数,而且只会调用一次
#include"stdafx.h"
#include<string>
#include<iostream>
using namespace std;
class person
{
public:
person()
{
cout<<"打印构造函数"<<endl;
}
~person()
{
cout<<"析构函数调用"<<endl;
}
};
int main()
{
person p;
}
结果
打印构造函数
析构函数调用
请按任意键继续. . .
函数调用三大方法{括号,显示,隐式}
括号法
#include"stdafx.h"
#include<string>
#include<iostream>
using namespace std;
class person
{
public:
person()
{
cout<<"无参构造函数"<<endl;
}
person(int a)
{
age=a;
cout<<"有参构造函数"<<endl;
}
person(const person &p)
{
age=p.age;
cout<<"拷贝函数调用"<<endl;
}
~person()
{
cout<<"析构函数调用"<<endl;
}
int age;
};
void main()
{
person p;
person p2(10);
person p3(p2);
cout<<"年龄为"<<p2.age<<endl;
cout<<"年龄为"<<p3.age<<endl;
}
显示法
void main()
{
person p;
person p2=person(10);
person p3=person(p2);
}
隐式法
void main()
{
person p4=10;
person p5=p4;
}