C ++类

定义一个Person类,私有成员int age,string &name,定义一个Stu类,包含私有成员double *score,写出两个类的构造函数、析构函数、拷贝构造和拷贝赋值函数,完成对Person的运算符重载(算术运算符、条件运算符、逻辑运算符、自增自减运算符、插入/提取运算符)

#include <iostream>

using namespace std;

class person
{
    int age;
    string &name;
public:
    person(string &a):age(18),name(a){}
    person(int a,string &b):age(a),name(b){}
    ~person(){}
    person(const person &other):age(other.age),name(other.name){}
    person &operator=(const person&other)
    {
        this->age=other.age;
        this->name=other.name;
        return *this;
    }
    void show()
    {
        cout<<"age:"<<age<<endl<<"name:"<<name<<endl;
    }
    person operator+(const person&other)
    {
        int age=this->age+other.age;
        static string name;
        name = this->name+other.name;
        return person(age,name);
    }
    bool operator==(person &other)
    {
        if((this->age==other.age)&&(this->name==other.name))
            return true;
        else
            return false;
    }
    bool operator>(person &other)
    {
        if(this->age>other.age)
            return true;
        else
            return false;
    }
    bool operator&&(person &other)
    {
        return (this->age&&other.age)||(this->name==other.name);
    }
    int getage(){return age;}
    friend ostream &operator<<(ostream &out,person&c1);
    friend istream &operator>>(istream &in,person &c1);
};
ostream &operator<<(ostream &out,person&c1)
{
    out<<"age:"<<c1.age<<endl<<"name:"<<c1.name<<endl;
    return out;
}
istream &operator>>(istream &in,person &c1)
{
    in>>c1.age>>c1.name;
    return in;
}
class stu
{
    double *score;
    person p1;
public:
    stu(string &a):score(new double(12.5)),p1(a){}
    stu(double a,string &b):score(new double(a)),p1(b){}
    ~stu(){delete score;}
    stu(const stu&other):score(new double(*(other.score))),p1(other.p1){}
    stu &operator=(const stu&other)
    {
        *(this->score)=*(other.score);
        this->p1=other.p1;
        return *this;
    }
    void show()
    {
        cout<<"score:"<<*score<<endl;
        p1.show();
    }
};
int main()
{
    string a="zhangsan";
    string b="lisi";
    string c="wangwu";
    stu a1(a);
    a1.show();
    cout<<endl;
    person p1(a);
    cout<<p1<<endl;
    person p2(b);
    cout<<p2<<endl;
    person p3(c);
    cout<<p3<<endl;
    person p4=(p1+p2);
    p4.show();
    cout<<endl;
    cout<<(p1==p2)<<endl;
    cout<<(p1>p2)<<endl;
    cout<<(p1&&p2)<<endl;

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值