构造函数与析构函数

1.构造函数
C++中有这么一种特殊的函数,它在类里,与类名同名,且没有返回值的一个函数,只要我们定义一个类的对象,系统就会自动调用它,进行专门的初始化对象用,而大多数情况下,因为我们没有定义构造函数,系统会默认生成一个默认形式、隐藏着的构造函数,这个构造函数的函数体是空着的,因此不具有任何功能。

那么下来,我们将教大家如何定义自己的构造函数,需要用户自行定义了至少一个构造函数,系统就不在自动生成,而是根据用户定义的构造函数选择最匹配的一个进行调用。

例如还是Student类的例子,我们添加一个带有默认参数的构造函数,代码如下:

#include<iostream>
#include<Cstring>
using namespace std;
class Student
{
    private:
    int num;//学号
    char name[100];//名字
    int score;//成绩
    public:
    Student(int n,char *str,int s);
    int print();
    int Set(int n,char *str,int s);
};
Student::Student(int n,char *str,int s)
{
     num = n;
     strcpy(name,str);
     score = s;
cout<<"Constructor"<<endl;
}
int Student::print()
{
    cout<<num<<" "<<name<<" "<<score;
    return 0;
}
int Student::Set(int n,char *str,int s)
{
     num = n;
     strcpy(name,str);
     score = s;
}
int main()
{
    Student A(100,"dotcpp",11);//定义的时候同时调用
    A.print();
    return 0;
}

在这里插入图片描述
2.析构函数

与构造函数不同的是,虽然他俩都为公开类型。构造可以重载,有多个兄弟,而析构却不能重载,但它可以是虚函数,一个类只能有一个析构函数。

下面,我们以Student类为例,继续添加析构函数,同时在构造函数和析构函数中都添加了输出当前类的信息,用来辨别哪一个类的创建和销毁:

#include<iostream>
#include<Cstring>
using namespace std;
class Student
{
private:
    int num;//学号
    char name[100];//名字
    int score;//成绩
public:
    Student(int n,char *str,int s);
    ~Student();
    int print();
    int Set(int n,char *str,int s);
};
Student::Student(int n,char *str,int s)
{
     num = n;
     strcpy(name,str);
     score = s;
     cout<<num<<" "<<name<<" "<<score<<" ";
     cout<<"Constructor"<<endl;
}
Student::~Student()
{
    cout<<num<<" "<<name<<" "<<score<<" ";
    cout<<"destructor"<<endl;
}
int Student::print()
{
    cout<<num<<" "<<name<<" "<<score<<endl;
    return 0;
}
int Student::Set(int n,char *str,int s)
{
     num = n;
     strcpy(name,str);
     score = s;
}
int main()
{
    Student A(100,"dot",11);
    Student B(101,"cpp",12);
    return 0;
}

在这里插入图片描述
可以看到对象A和B的构造函数的调用顺序以及构造函数的调用顺序,完全相反!原因在于A和B对象同属局部对象,也在栈区存储,也遵循“先进后出”的顺序!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值