1 #include<iostream> 2 #include<string> 3 using namespace std; 4 /* 5 //成员变量私有化优点: 6 1.控制成员的读写权限 7 2.检测读写有效性 8 9 */ 10 class Point 11 { 12 public://控制成员的读写权限 13 void setX(int x) 14 { 15 m_X = x; 16 } 17 int getX() 18 { 19 return m_X; 20 } 21 void setY(int y) 22 { 23 if (y<5)//检测读写有效性 24 { 25 cout << "Y值小于5" << endl; 26 m_Y = 0; 27 return; 28 } 29 m_Y = y; 30 } 31 int getY() 32 { 33 return m_Y; 34 } 35 private://成员变量私有化 36 int m_X; 37 int m_Y; 38 }; 39 40 int main() 41 { 42 Point pt; 43 int x,y; 44 cout << "请输入x :\n"; 45 cin >> x; 46 cout << "请输入y(y值大于5,如果小于5置为0) :\n"; 47 cin >> y; 48 49 pt.setX(x); 50 pt.setY(y); 51 52 cout << "X值:" << pt.getX() << endl; 53 cout << "Y值:" << pt.getY() << endl; 54 55 system("pause"); 56 return 0; 57 }
类成员变量私有化
原文:https://www.cnblogs.com/rtblogs/p/12000900.html