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;
}

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