zoukankan      html  css  js  c++  java
  • C++(运算符重载+)

    1.加号运算符重载

    • 实现自定义数据类型的加运算
    
    #include <iostream>
    using namespace std;
    
    
    class Person {
    public:
    	int m_A, m_B;
    
    	//1.成员函数重载+号
    	Person operator+(const Person &p) {
    		Person temp;
    		temp.m_A = this->m_A + p.m_A;
    		temp.m_B = this->m_B + p.m_B;
    		return temp;
    	}
    
    };
    
    //2.全局运算符重载
    //Person operator+(const Person &p1, const Person &p2) {
    //	Person temp;
    //	temp.m_A = p1.m_A + p2.m_A;
    //	temp.m_B = p1.m_B + p2.m_B;
    //	return temp;
    //}
    
    //3.运算符也可以发生函数重载
    Person operator+(const Person &p, int num) {
    	Person temp;
    	temp.m_A = p.m_A + num;
    	temp.m_B = p.m_B + num;
    	return temp;
    }
    
    //4.测试函数
    void test()
    {
    	Person p1, p2;
    	p1.m_A = 10;
    	p1.m_B = 10;
    
    	p2.m_A = 20;
    	p2.m_B = 20;
    
    	//成员函数方式
    	Person p3 = p2 + p1; //相当于p3=p2.operator+(p1)
    	cout << "p3.mA: " << p3.m_A << "p3.m_B " << p3.m_B << endl;
    
    	//运算符函数重载
    	Person p4 = p3 + 10; //相当于p4=p3.operator+(num)
    	cout << "p4.mA: " << p4.m_A << "p4.m_B " << p4.m_B << endl;
    }
    int main()
    {
    	test();
        std::cout << "Hello World!
    ";
    }
    

    总结

    • 1,对于内置数据类型的表达式的运算符是不可能改变的
    • 2,不要滥用运算符重载
  • 相关阅读:
    PHP文件上传代码和逻辑详解
    了解thinkphp(二)
    了解ThinkPHP(一)
    php关于static关键字
    php关于return的关键字
    会话控制
    PDO数据库
    PHP包含文件函数include、include_once、require、require_once区别总结
    jQuery事件
    一、MVC模式学习概述
  • 原文地址:https://www.cnblogs.com/xuelanga000/p/14296919.html
Copyright © 2011-2022 走看看