1.30 C++ day4

思维导图

1.30 C++ day4_第1张图片

构造函数、析构函数、拷贝构造函数、拷贝赋值函数

代码

#include 

using namespace std;

class Stu//封装一个学生类
{
private://私有属性
    string name;
    int id;
    double *score;
public://公共属性
    //无参构造函数
    Stu(){cout << "Stu::无参构造函数" << endl;}
    //有参构造函数
    Stu(string name,int id,double score):name(name),id(id),score(new double(score))//初始化列表
    {
        cout << "Stu::有参构造函数" << endl;
    }
    //拷贝构造函数
    Stu(const Stu &other):name(other.name),id(other.id),score(new double(*other.score))//初始化列表
    {
        //score=new double(*other.score);
        cout << "Stu::拷贝构造函数" << endl;
    }
    //拷贝赋值函数
    Stu &operator=(const Stu &other)
    {
        if(this!=&other)//防止自己给自己赋值
        {
            name=other.name;
            id=other.id;
            score=new double(*other.score);//深拷贝
        }
        cout << "Stu::拷贝赋值函数" << endl;
        return *this;
    }
    //析构函数
    ~Stu()
    {
        cout << "Stu::析构函数" << endl;
        delete score;
    }
    void show()
    {
        cout << "name:" << name << ",";
        cout << "id:" << id << ",";
        cout << "score:" << *score << endl;
    }
};

int main()
{
    Stu s1,s4,s5;//自动调用s1.Stu()
    Stu s2("张三",1001,85.58);//自动调用s2.Stu("张三",1001,85.58)
    cout << "s2:";
    s2.show();
    Stu s3(s2);//s3.Stu(s2)
    cout << "s3:";
    s3.show();
    s1=s3;//自动调用拷贝赋值函数==>s1.operator(s3)
    cout << "s1:";
    s1.show();
    return 0;
}

 结果

1.30 C++ day4_第2张图片

你可能感兴趣的:(c++,开发语言)