c++訪問私有(private)成員變數的常用方法
阿新 • • 發佈:2018-12-26
類的物件不能直接訪問類宣告的私有成員變數,否則破壞了資訊隱藏的目的。
在C++中,為了防止某些資料成員或成員函式從外部被直接訪問,可以將它們宣告為private,這樣編譯器會阻止任何來自外部非友元的直接訪問。
私有成員變數的常用訪問方法如下:
(1)通過公共函式為私有成員賦值
(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 print(void) { cout<<"x="<<x<<'\t'<<"y="<<y<<endl; } } ; int main() { Test p1; p1.setX(1); p1.setY(9); p1.print( ); 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; } void getXY(int *px, int *py) { *px=x; //提取x,y值 *py=y; } }; int main() { Test p1; p1.setX(1); p1.setY(9); int a,b; p1.getXY(&a,&b); //將 a=x, b=y cout<<a<<'\t'<<b<<endl; return 0; }
#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(1); p1.setY(9); int a,b; a=p1.getX( ); b=p1.getY(); cout<<a<<'\t'<<b<<endl; return 0; }
(4)利用引用訪問私有資料成員
#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(1);
p1.setY(9);
int a,b;
p1.getXY(a, b); //將 a=x, b=y
cout<<a<<'\t'<<b<<endl;
return 0;
}