• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

深入解析C++中的构造函数和析构函数

c++ 搞代码 4年前 (2022-01-06) 36次浏览 已收录 0个评论

析构函数:在撤销对象占用的内存之前,进行一些操作的函数。析构函数不能被重载,只能有一个

构造函数:
在类实例化对象时自动执行,对类中的数据进行初始化。构造函数可以从载,可以有多个,但是只能有一个缺省构造函数。

析构函数:
在撤销对象占用的内存之前,进行一些操作的函数。析构函数不能被重载,只能有一个。

调用构造函数和析构函数的顺序:
先构造的后析构,后构造的先折构。它相当于一个栈,先进后出。

代码如下:
#include
#include
using namespace std;
class Student{
 public:
  Student(string,string,string);
  ~Student();
  void show();
 private:
  string num;
  string name;
  string sex;
};
Student::Student(string nu,string na,string s){
 num=nu;
 name=na;
 sex=s;
 cout<<name<<" is builded!"<<endl;
}
void Student::show(){
 cout<<num<<"\t"<<name<<"\t"<<sex<<endl;
}
Student::~Student(){
 cout<<name<<" is destoried!"<<endl;
}
int main(){
 Student s1(“001″,”千手”,”男”);
 s1.show();
 Student s2(“007″,”纲手”,”女”);
 s2.show();
 cout<<"nihao"<<endl;
 cout<<endl;
 cout<<"NIHAO"<<endl;
 return 0;
}

先构造的千手,结果后析构的千手;后构造的纲手,结来源gaodai$ma#com搞$$代**码网果先折构的纲手。

特点:
在全局范围定义的对象和在函数中定义的静态(static)局部对象,只在main函数结束或者调用exit函数结束程序时,才调用析构函数。

如果是在函数中定义的对象,在建立对象时调用其构造函数,在函数调用结束、对象释放时先调用析构函数。

代码如下:
#include
#include
using namespace std;
class Student{
 public:
  Student(string,string);
  ~Student();
  void show();
  string num;
  string name;
};
Student::Student(string nu,string na){
 num=nu;
 name=na;
 cout<<name<<" is builded!"<<endl<<endl;
}
void Student::show(){
 cout<<num<<"\t"<<name<<endl<<endl;
}
Student::~Student(){
 cout<<name<<" is destoried!"<<endl<<endl;
}
void fun(){
 cout<<"============调用fun函数============"<<endl<<endl;
 Student s2(“002″,”自动局部变量”);//定义自动局部对象
 s2.show();
 static Student s3(“003″,”静态局部变量”);//定义静态局部变量
 s3.show();
 cout<<"===========fun函数调用结束=============="<<endl<<endl;
}
int main(){
 Student s1(“001″,”全局变量”);
 s1.show();
 fun();
 cout<<"\nthis is some content before the end\n";//这是一段位于main函数结束之前,函数调用之后的内容
 cout<<endl;
 return 0;
}

以上就是深入解析C++中的构造函数和析构函数的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:深入解析C++中的构造函数和析构函数

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址