c++重载

自增运算符重载

#include <iostream>
using namespace std;
class Person {
   friend ostream& operator<<(ostream &cout, Person p);
public:
    Person(int x) {
        m_Age = x;
    }
    //前置++运算符重载
    Person& operator++() {
        m_Age++;
        return *this;
    }

    //后置++运算符
    Person operator++(int) {
        //先记录当时结果

        Person temp = *this;

        m_Age++;
        return temp;
    }


private:
    int m_Age;
};


ostream& operator<<(ostream &cout,Person p) {

    cout << p.m_Age;
    return  cout;
}


void test1() {
    Person p1(10);
    cout << ++p1<<endl;

}



void test2() {
    Person p1(10);
    cout << p1++ << endl;
    cout << p1 << endl;

}

int main()
{
    //test1();
    test2();
    

    //std::cout << "Hello World!\n";
}

赋值运算符重载

// ConsoleApplication8.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
using namespace std;
class Person {
   friend ostream& operator<<(ostream &cout, Person p);
public:
    Person(int x) {
        m_Age = new int(x);
    }

    ~Person() {
        while (m_Age != NULL) {
            delete m_Age;
            m_Age = NULL;
        }
    }
    //赋值运算符重载
    Person & operator=(Person& p) {
        //应该先判断是否有属性在堆区
        if (m_Age != NULL) {
            delete m_Age;
            m_Age = NULL;
        }
        this->m_Age = new int(*p.m_Age);
        //返回对象本身
        return *this;
    }

public:
    int *m_Age;
};



void test01() {
    Person p1(10);
    Person p2(20);
    Person p3(30);
   p3= p2 = p1;
    cout << *p1.m_Age << endl;
    cout << *p2.m_Age << endl;
    cout << *p3.m_Age << endl;
}


int main()
{
    test01();
    //test2();
    

    //std::cout << "Hello World!\n";
}



关系运算符重载



#include <iostream>
using namespace std;
class Person {
  
public:
    Person(int x,string str) {
        m_Age = x;
        m_Name = str;
    }

    ~Person() {
      
    }
  
    //关系运算符重载,==
    bool operator==(Person &p) {
        if (this->m_Age == p.m_Age && this->m_Name == p.m_Name) {
            return true;
        }
        else {
            return false;
        }
    }

private:
    int m_Age;
    string m_Name;
};
void test01() {
    Person p1(10,"张三");
    Person p2(10,"张三");
    if (p1 == p2) {
        cout << "两个对象相等" << endl;
    }
    else {
        cout << "两个对象不相等" << endl;
    }
  
}


int main()
{
    test01();
    //std::cout << "Hello World!\n";
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值