如何突破class的private属性限制——试图破坏class的封装性,有点“逆天而行”的感觉。
方法1. 添加友元函数
#include<iostream>
using namespace std;
class X
{
private:
int m_Age;
public:
X() : m_Age(1){}
template<typename T>
void Func(const T &t){}
const int GetValue()
{
return m_Age;
}
friend void Func(X* xPtr);
};
void Func(X* xPtr)
{
xPtr->m_Age = 2;
}
int main() {
X x;
cout << x.GetValue() << endl;// 输出1
Func(&x);
cout << x.GetValue() << endl;// 输出2
getchar();
return 0;
}
使用友元函数,应该是最先想到的解决方案。
类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。
方法2. 使用指针类型转换——偷天换日
#include<iostream>
using namespace std;
class X
{
private:
int m_Age;
public:
X() : m_Age(1){}
template<typename T>
void Func(const T &t){}
const int GetValue()
{
return m_Age;
}
};
// 同X的内存布局,将变量的类型定义改为pub