第三周课后实践-阅读程序

按照封装与信息隐藏的原则,除非特别需要,类中的数据成员需要设置为私有。由此带来的问题是,在类外如何访问这些私有成员?下面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

原文地址:https://www.cnblogs.com/mayuko/p/4567534.html