zoukankan      html  css  js  c++  java
  • 运算符重载方法1

    #include <iostream>
    
    /* run this program using the console pauser or add your own getch, system("pause") or input loop */
    class A
    {
        public:
            A();
            A(int initialValue);
            A add(const A & src);
            void setValue(int value);
            int show();
        private:
            int mValue;
    };
    
    A::A()
    :mValue(0)
    {
        
    }
    A::A(int initialValue)
    :mValue(initialValue)
    {
        
    }
    void A::setValue(int value)
    {
        mValue = value;
    }
    A A::add(const A & src)
    {
        A newA;
        newA.setValue(mValue + src.mValue);
        return newA;
    }
    int A::show()
    {
        std::cout << "value : " << mValue << std::endl;
    }
    
    
    int main(int argc, char** argv) 
    {
        A a1(4);
        A a2(5);
        A a3 = a1.add(a2);
        a1.show();
        a2.show();
        a3.show();
        return 0;
    }

    结果是:

    value : 4
    value : 5
    value : 9

    在方法的是现实中创建了一个newA的A,返回的是newA而不是newA的引用,否则程序报错,因为add()方法结束后newA超出作用域,因此被销毁返回引用将会是悬挂引用。

  • 相关阅读:
    Python使用asyncio+aiohttp异步爬取猫眼电影专业版
    Django
    Django
    Vue 1-- ES6 快速入门、vue的基本语法、vue应用示例,vue基础语法
    Django
    Django
    Django
    Django
    django--权限(1)初识
    Django
  • 原文地址:https://www.cnblogs.com/boost/p/10333594.html
Copyright © 2011-2022 走看看