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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值