有关C++封装的一些误区

以类为单位的封装


C++的封装是以类为单位的,而不是以对象为单位的

同一个类的不同对象可以互相访问私有成员

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>
using namespace std;

class TestClass
{
public:
void GetPrivateValue(TestClass &other)
{
this->value = other.value;
}

void SetValue(int value)
{
this->value = value;
}

int GetValue()
{
return value;
}

private:
int value;
};

int main()
{
TestClass A,B;
B.SetValue(5);
A.GetPrivateValue(B);
cout<<A.GetValue()<<' '<<B.GetValue();
return 0;
}
  • © 2018-2020 宇亓
  • Powered by Hexo Theme Ayer
    • PV:
    • UV:

请我喝杯咖啡吧~

支付宝
微信