公共函数是否可以返回指向类中私有变量的指针.如果是这样/如果没有,会发生什么?它会崩溃还是有什么高度不安全的?可以读取或写入指向的数据吗?谢谢
Jam*_*lis 23
是的,成员函数可以将指针(或引用)返回给私有数据成员.这没有什么不妥,除了在大多数情况下它破坏了封装.
当然可以通过返回的指针或引用来读取数据成员.是否可以写入取决于返回的指针或引用是否是const限定对象(即,如果返回a const T*,则无法修改指向的对象T).例如:
class Example
{
public:
int* get() { return &i; }
const int* get_const() const { return &i; }
private:
int i;
};
int main()
{
Example e;
int* p = e.get();
int a = *p; // yes, we can read the data via the pointer
*p = 42; // yes, we can modify the data via the pointer
const int* cp = e.get_const();
int b = *cp; // yes, we can read the data via the pointer
*cp = 42; // error: pointer is to a const int
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7207 次 |
| 最近记录: |