zoukankan      html  css  js  c++  java
  • 第三周课后实践-阅读程序

    按照封装与信息隐藏的原则,除非特别需要,类中的数据成员需要设置为私有。由此带来的问题是,在类外如何访问这些私有成员?下面4段程序概括了常用的方法。请仔细阅读下面的程序,在阅读过程中,画出对象、变量在内存中的表示图,写出这些程序的运行结果(包括变量的变化过程及程序的最终输出),达到彻底理解这些机制的目标。

    (1)通过公共函数为私有成员赋值

    #include <iostream>
    using namespace std;
    class Test
    {
    private:
        int x, y;
    public:
        void setX(int a)
        {
            x=a;
        }
        void setY(int b)
        {
            y=b;
        }
        void printXY(void)
        {
            cout<<"x="<<x<<'	'<<"y="<<y<<endl;
        }
    } ;
    int main()
    {
        Test p1;
        p1.setX(3);
        p1.setY(5);
        p1.printXY( );
        return 0;
    }


    (2)利用指针访问私有数据成员

    #include <iostream>
    using namespace std;
    class Test
    {
    private:
        int x,y;
    public:
        void setX(int a)
        {
            x=a;
        }
        void setY(int b)
        {
            y=b;
        }
        void getXY(int *px, int *py)
        {
            *px=x;    //提取x,y值
            *py=y;
        }
    };
    int main()
    {
        Test p1;
        p1.setX(3);
        p1.setY(5);
        int a,b;
        p1.getXY(&a,&b);  //将 a=x, b=y
        cout<<a<<'	'<<b<<endl;
        return 0;
    }
    


    (3)利用函数访问私有数据成员

    #include <iostream>
    using namespace std;
    class Test
    {
    private:
        int x,y;
    public:
        void setX(int a)
        {
            x=a;
        }
        void setY(int b)
        {
            y=b;
        }
        int getX(void)
        {
            return x;   //返回x值
        }
        int getY(void)
        {
            return y;   //返回y值
        }
    };
    int main()
    {
        Test p1;
        p1.setX(3);
        p1.setY(5);
        int a,b;
        a=p1.getX( );
        b=p1.getY();
        cout<<a<<'	'<<b<<endl;
        return 0;
    }
    


    (4)利用引用访问私有数据成员

    #include <iostream>
    using namespace std;
    #include <iostream>
    using namespace std;
    class Test
    {
    private:
        int x,y;
    public:
        void setX(int a)
        {
            x=a;
        }
        void setY(int b)
        {
            y=b;
        }
        void getXY(int &px, int &py) //引用
        {
            px=x;    //提取x,y值
            py=y;
        }
    };
    int main()
    {
        Test p1,p2;
        p1.setX(3);
        p1.setY(5);
        int a,b;
        p1.getXY(a, b); //将 a=x, b=y
        cout<<a<<'	'<<b<<endl;
        return 0;
    }
    


    @ Mayuko

  • 相关阅读:
    3--Selenium环境准备--Eclipse 引入 selenium-server包
    2--Selenium环境准备--第一次使用Testng
    1--Selenium环境准备--Eclipse 添加Testng插件
    2--Jmeter 4.0--Excel 数据驱动 接口测试
    1--Jmeter4.0连接Oracle数据库
    冲刺第六天
    构建执法阅读笔记5
    学习进度八
    冲刺第五天
    冲刺第四天
  • 原文地址:https://www.cnblogs.com/mayuko/p/4567534.html
Copyright © 2011-2022 走看看