问题:C++获取类中的变量的方法(变量公有化【public变量】&&使用set和get函数)

本程序通过VC++ 6.0编译与测试,程序中Point类中的x,y均为私有化变量,对应主函数中的set与get函数,z变量为共有变量和直接访问,具体代码如下:

#include <iostream>
using namespace std;
 class Point
 {
 private:
	 float x;
	 float y;//private不可以被直接访问,需要使用set函数修改或者get函数获取
 public:
	 float z;//public 变量可以直接访问,对应cout<<"result of trans to public: "<<p1.z<<endl;语句
	 Point()
	 {
		 x=0;
		 y=0;
		 z=4;
	 }
	 void setXY(float _x,float _y)
	 {
		 x=_x;
		 y=_y;
	 }
	 float getX()
	 {
		 return x;
	 }
	 float getY()
	 {
		 return y;
	 }
	 void printPoint()
	 {
		 cout<<"("<<x<<","<<y<<")"<<endl;
	 }
 };

 int main()
 {
	 Point p1;
	 cout<<"result of use get:("<<p1.getX()<<","<<p1.getY()<<")"<<endl;//不能直接使用(P1.X=1)修改函数值,需要使用set函数
	 p1.setXY(1,1);
	 cout<<"result of use set:";
	 p1.printPoint();
	 cout<<"result of trans to public: "<<p1.z<<endl;
	 return 0;
 }