类。。。。

发布时间:2023年12月28日

定义一个person类,包含私有成员,int *age,string &name,一个stu类,包含私有成员double *sore,person p1,写出person类和stu类的特殊成员函数,并写一个stu的函数,显示所有信息。

#include <iostream>

using namespace std;
class person
{
    int *age;
    string &name;
public:
    person(string &a):age(new int(18)),name(a){cout<<"调用person一个参数的构造函数"<<endl;}
    person(int a,string &b):age(new int(a)),name(b){cout<<"调用person两个参数的构造函数"<<endl;}
    person (const person &other):age(new int(*(other.age))),name(other.name){}
    ~person(){delete age;cout<<"调用person析构函数"<<endl;}
    person &operator=(const person &other)
    {
        *(this->age)=*(other.age);
        this->name=other.name;
        return *this;
    }
    int getage();
    string getname();
};
int person::getage()
{
    return *age;
}
string person::getname()
{
    return name;
}
class stu
{
    double *score;
    person p1;
public:
    stu(string &a):score(new double(99.5)),p1(a){cout<<"调用stu一个参数的构造函数"<<endl;}
    stu(double a,string &b):score(new double(a)),p1(b){cout<<"调用stu两个参数的构造函数"<<endl;}
    stu(double a,int b,string &c):score(new double(a)),p1(b,c){cout<<"调用stu三个参数的构造函数"<<endl;}
    stu(const stu &other):score(new double(*(other.score))),p1(other.p1){cout<<"调用stu拷贝构造函数"<<endl;}
    ~stu(){delete score;cout<<"调用stu析构函数"<<endl;}
    stu &operator=(const stu &other)
    {
        *(this->score)=*(other.score);
        this->p1=other.p1;
        cout<<"调用stu拷贝赋值函数"<<endl;
        return *this;
    }
    void show();
};
void stu::show()
{
    cout<<p1.getname()<<"\t"<<p1.getage()<<"\t"<<*score<<endl;

}
int main()
{
    string a="杜甫";
    string b="李白";
    stu a1(a);
    a1.show();
    stu a2=a1;
    a2.show();
    stu a3(a);
    a3=a2;
    a3.show();
    stu *p=new stu(80.5,20,b);
    p->show();
    delete p;
    return 0;
}

文章来源:https://blog.csdn.net/m0_64059184/article/details/135276884
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。