您的位置:首页 > 编程语言 > C语言/C++

C++私有数据成员提取到类外的方法总结

2015-04-10 15:58 337 查看
今天接触到了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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: