C++ DAY3 作业

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

#include 

using namespace std;

class Person
{
    int *age;
    string &name;  //存在引用成员
public:
    //构造函数
    Person(string name):age(new int),name(name)
    {
        cout << "Person一个参数的有参构造" << endl;
    }
    Person(int age,string name):age(new int(age)),name(name)
    {
        cout << "Person两个参数的有参构造" << endl;
    }
    //析构函数
    ~Person(){
        delete age;
        cout << "Person的析构函数,释放空间:" << age << endl;
    }
    //拷贝构造函数
    Person(const Person&other):age(new int(*(other.age))),name(other.name)
    {
        cout << "Person的拷贝构造函数" << endl;
    }
    //拷贝赋值函数
    Person &operator = (const Person &other)
    {
        *(this->age) = *(other.age);
        this->name = other.name;
        cout << "Person的拷贝赋值函数" << endl;
        return *this;
    }
    int get_age();
    string get_name();
};
int Person::get_age()
{
    return *age;
}
string Person::get_name()
{
    return name;
}

class Stu
{
    double *score;
    Person p1;
public:
    //构造函数
    Stu():score(new double),p1(p1)
    {cout << "Stu的无参构造" << endl;}
    Stu(double score):score(new double(score)),p1(p1)
    {cout << "Stu的一个参数有参构造" << endl;}
    Stu(double score,Person p1):score(new double(score)),p1(p1)
    {cout << "Stu的两个参数有参构造" << endl;}
    //析构函数
    ~Stu(){
        delete score;
        cout << "Stu的析构函数,释放空间:" << score << endl;
    }
    //拷贝构造函数
    Stu(const Stu &other):score(new double(*(other.score))),p1(other.p1)
    {
        cout << "Stu的拷贝构造函数" << endl;
    }
    //拷贝赋值函数
    Stu &operator =(const Stu &other)
    {
        *(this->score) = *(other.score);
        this->p1 = other.p1;
        cout << "Stu的拷贝赋值函数" << endl;
        return *this;
    }
    void show(Person p1);
};
void Stu::show(Person p1)
{
    cout << "age:" << p1.get_age() << endl;
    cout << "name:" << p1.get_name() << endl;
    cout << "score:" << *score << endl;
}


int main()
{
    Person p1(18,"zhangsan");
    //Stu s1;
   Stu s2(50);
    s2.show(p1);
//    Person p2("lisi");
//    p2 = p1;
    //Person p2 = p1;

    return 0;
}

C++ DAY3 作业_第1张图片

2.思维导图

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