C++私有數據成員提取到類外的方法總結

今天接觸到了C++的引用使用方法,C++中的數據成員(也可以成長爲對象的屬性,當然成員函數就叫做對屬性施加的行爲)分爲public,protected和private三種咯。private數據成員是不能被類外的函數進行操作的(友元除外),今把我做學到和接觸的類的私有數據成員提取的類外的方法進行總結,由於水平有限,熱烈歡迎各位朋友補充:

#include <iostream>

using namespace std;

class Test
{
public:
    void set(int,int);
    void display();
    //將對象私有數據成員取出方式一,引用
    void getxy(int &a,int &b)
    {
        a=x;
        b=y;
    }
//將對象私有數據成員取出方式一,指針
    void getxy1(int *a,int *b)
    {
        *a=x;
        *b=y;
    }
    //將對象私有數據成員取出方式一,return
    int getx()
    {
return x;
    }

    int gety()
    {
return y;
    }
private:
    int x;
    int y;
};

void Test:: set(int a,int b)
{
    x=a;
    y=b;
}

void Test:: display()
{
    cout<<"x="<<x<<endl;
    cout<<"y="<<y<<endl;
}
int main()
{
   Test test1;
   test1.set(1,2);
   test1.display();
   int a,b;
   test1.getxy(a,b);
   cout<<"a="<<a<<'\t'<<"b="<<b<<endl;

   int c,d;
   test1.getxy1(&c,&d);
   cout<<"c="<<a<<'\t'<<"d="<<b<<endl;

int x,y;
   cout<<"x="<<test1.getx()<<'\t'<<"y="<<test1.gety()<<endl;

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章