您的位置:首页 > 其它

第三周 阅读程序

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

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

[cpp] view
plaincopyprint?





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<<'\t'<<"y="<<y<<endl;

}

} ;

int main()

{

Test p1;

p1.setX(3);

p1.setY(5);

p1.printXY( );

return 0;

}

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

[cpp] view
plaincopyprint?





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<<'\t'<<b<<endl;

return 0;

}

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

[cpp] view
plaincopyprint?





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<<'\t'<<b<<endl;

return 0;

}

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

[cpp] view
plaincopyprint?





#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<<'\t'<<b<<endl;

return 0;

}

运行结果:






内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: