在C++中访问类的私有成员变量的方法有哪些

2025-03-24 15:16:06
推荐回答(2个)
回答(1):

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

#include     
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="<    }    
} ;   
  
int main()    
{    
    Test p1;    
    p1.setX(1);    
    p1.setY(9);    
    p1.print( );    
    return 0;    
}

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

#include     
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<   return 0;    
}

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

#include     
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<    return 0;    
}

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

#include     
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<    return 0;    
}

回答(2):

成员函数,友元函数。