c++ / day03

1. 定义一个Person类,包含私有成员,int *age,string &name,一个Stu类,包含私有成员double *score,Person p1,写出Person类和Stu类的特殊成员函数,并写一个Stu的show函数,显示所有信息。

代码: updated

#include <iostream>

using namespace std;

class Person
{
    int *_ptr_age;
    string &_ref_name;
public:
    //Person constructor,
    Person(int age, string &ref_name):_ptr_age(new int(age)), _ref_name(ref_name)
    {
        cout << "Person constructor with 2 params" << endl;
    }

    //destructor
    ~Person()
    {
       cout << "Person destructor" << endl;
       delete _ptr_age;

    }

    //copy constructor. Note: param need to be initilized for space
    Person(const Person &src):_ptr_age(new int(*(src._ptr_age))), _ref_name(src._ref_name)
    {

        cout << "Person copy constructor" << endl;
    }

    //assign constructor. Note it has been initilized, has space alread, just need copy value
    Person &operator=(const Person &src)
    {
        this->_ptr_age =src._ptr_age;
        this->_ref_name = src._ref_name;
      cout << "Person assign constructor" << endl;
      return *this;
    }

    int get_age();
    string get_name();
};

class Stu
{
    double *_ptr_score;
    Person _person;

public:
    //constuctor
    Stu(double score, int age, string name):_ptr_score(new double (score)), _person(age, name)
    {
        cout << "Stu constructor with 2 params" << endl;
    }
    //destructor
    ~Stu()
    {
       cout << "Stu destructor" << endl;
       delete _ptr_score;
    }
    //copy constructor
    Stu(const Stu &src):_ptr_score(new double(*(src._ptr_score))), _person(src._person)
    {
        cout << "Stu copy constructor" << endl;
    }

    //assign constructor
    Stu &operator = (const Stu &src)
    {
        this->_ptr_score = src._ptr_score;
        this->_person = src._person;
        return *this;
    }



    void show();
};

int Person::get_age()
{
    return *_ptr_age;
}

string Person::get_name()
{
    return _ref_name;
}

void Stu::show()
{
    cout << "score = "<< *_ptr_score << endl;
    cout << "person age = "<< _person.get_age() << endl;
    cout << "person name = "<< _person.get_name() << endl;

}


int main()
{
    int age = 28;
    string name = "zhangsan";

    double score = 99;
    Stu *stu_zs = new Stu(score, age, name);
    stu_zs->show();

    delete stu_zs;

    return 0;
}

运行结果

2. 整理思维导图(从特殊成员函数的角度出发整理)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值