12.29

本文详细介绍了C++中的类Person和Stu,包括构造函数、析构函数、成员操作符重载以及如何进行对象的创建、复制和运算。展示了如何使用输入输出流操作类对象以及指针的使用。
摘要由CSDN通过智能技术生成
#include <iostream>

using namespace std;

class Person{
    int age;
    string &name;
public:
    Person(string &name):age(15),name(name){}
    Person(int age, string &name):age(age),name(name){}
    ~Person(){
        cout << "Person的析构函数" << endl;
    }
    Person(const Person &other):age(other.age),name(other.name){}
    Person &operator=(const Person &other){
        age = other.age;
        name = other.name;
        return *this;
    }
    Person operator+(const Person other){
        string tempname = name + other.name;
        int tempage = age + other.age;
        return Person(tempage, tempname);
    }
    bool operator==(const Person other){
        return age==other.age && name==other.name;
    }
    bool operator>=(const Person other){
        return age>=other.age && name>=other.name;
    }
    Person operator++(){
        age++;
        return *this;
    }
    Person operator++(int){
        return Person(age++, name);
    }
    Person operator--(){
        age--;
        return *this;
    }
    Person operator--(int){
        return Person(age--, name);
    }
    friend istream &operator>>(istream &cin, Person &p);
    friend ostream &operator<<(ostream &cout, Person &p);
};

istream &operator>>(istream &cin, Person &p){
    cin >> p.age >> p.name;
    return cin;
}

ostream &operator<<(ostream &cout, Person &p){
    cout << "age=" << p.age << ", name=" << p.name;
    return cout;
}

class Stu{
  double * const score;
public:
  Stu():score(new double(12.0)){}
  Stu(double score):score(new double(score)){}
  ~Stu(){
      delete score;
      cout << "Stu的析构函数" << endl;
  }
  Stu(Stu &other):score(new double(*(other.score))){}
  Stu &operator=(Stu &other){
      *score = *other.score;
      return *this;
  }
  void show(){
      cout << *score << endl;
  }
};

int main()
{
    string name1 = "a";
    Person p1(name1);
    cin >> p1;
    Person p2 = p1;
    cout << p2 << endl;
    p2++;
    cout << p2 << endl;
    string name2 = "b";
    Person p3(name2);
    cout << p3 << endl;
    p3 = p2 + p1;
    cout << boolalpha << (p2 == p1) << endl;
    cout << (p2 >= p1) << endl;
    cout << p3 << endl;
    cout << "-----------" << endl;
    Stu s1;
    s1.show();
    Stu s2(16.5);
    s2.show();
    Stu s3 = s2;
    s3.show();
    s2 = s1;
    s2.show();
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值