【C++编程】类与对象 -- 运算符重载:加号、左移运算符、递增运算符、函数调用运算符(仿函数) ...

  • 加号 +Person operator+(Person p);
    #include <iostream>
    using namespace std;
    
    class Person
    {
    public:
    	Person(int a, int b): m_A(a), m_B(b)
    	{
    	}
    	int m_A;
    	int m_B;
    	Person operator+(Person p)  // 通过成员函数重载 +
    	{
    		Person temp(0, 0);
    		temp.m_A = this->m_A + p.m_A;
    		temp.m_B = this->m_B + p.m_B;
    		return temp;
    	};
    };
    
    int main()
    {
    	Person p1(10, 20);
    	Person p2(10, 20);
    	Person p3 = p1 + p2;  // p3.m_A: 20, p3.m_B: 40  
    }
    
  • 左移运算符 <<ostream & operator<<(ostream &cout, Person p);
    #include <iostream>
    using namespace std;
    
    class Person
    {
    	friend ostream &operator<<(ostream &cout, Person p); // 如果涉及 private 成员
    
    public:
    	Person(int a, int b): m_A(a), m_B(b)
    	{
    	}
    	int m_A;
    	int m_B;
    };
    
    ostream & operator<<(ostream &cout, Person p) // 无法利用成员函数实现
    {
    	cout << " m_A = " << p.m_A << " m_B = " << p.m_B << endl;
    	return cout;
    }
    
    int main()
    {
    	Person p(10, 20);
    	cout << p << endl;  //  m_A = 10 m_B = 20
    }
    
  • 递增运算符 ++Person & operator++(), Person operator++(int)
    #include <iostream>
    using namespace std;
    
    class Person
    {
    public:
    	Person(int a, int b): m_A(a), m_B(b)
    	{
    	}
        Person & operator++()   // 前置递增,返回引用
        {
            this->m_A++;
            return *this;
        }
        Person operator++(int)  // 后置递增,返回值,参数 int 占位
        {
            Person temp = *this;
            this->m_A++;
            return temp;
        }
    	int m_A;
    	int m_B;
    };
    
    ostream & operator<<(ostream &cout, Person p)
    {
    	cout << " m_A = " << p.m_A << " m_B = " << p.m_B << endl;
    	return cout;
    }
    
    int main()
    {
    	Person p(10, 20);
    	cout << p << endl;   // m_A = 10 m_B = 20
    	cout << ++p << endl; // m_A = 11 m_B = 20
    	cout << p++ << endl; // m_A = 11 m_B = 20
    }
    
  • 函数调用运算符(): 自选返回类型 operator()(自选形参);
    #include <iostream>
    using namespace std;
    
    class Person
    {	
    public:
    	Person(int a, int b): m_A(a), m_B(b)
    	{
    	}
        void operator()()   // 函数调用运算符 -> 仿函数
        {
            cout << "here" << endl;
        }
    	int m_A;
    	int m_B;
    };
    
    
    int main()
    {
    	Person p(10, 20);
    	p();  
    }
    
  • 其他不赘述,仅给出 函数名称和参数返回类型
    • 赋值运算符=Person& operator=(Person p);
    • 关系运算符==bool operator==(Person p);

【黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难】

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值