引用和指针

来源:互联网 发布:即时聊天软件 行业 编辑:程序博客网 时间:2024/04/29 18:40

引用和指针

引用和指针引用的行为像一个const指针解引用一个有趣的关系式。从而给出如下

int nValue = 5;int *const pnValue = &nValue;int &rnValue = nValue;

同样,一个const引用的行为就像一个const指针指向const对象是隐式解引用

因为引用总是“点”来有效的对象,而不能指出释放内存,引用的是比使用指针安全。如果一个任务可以通过引用或指针解决,参考一般应首选。指针通常只能用引用是不充分的情况下(如动态分配的内存

成员的选择

通常有一个指针或引用一个结构(或类)。正如你已知道的你可以选择使用一个struct的成员选择运算符成员

struct Something{    int nValue;    float fValue;};// Member selection using actual struct variableSomething sSomething;sSomething.nValue = 5;// Member selection using reference to structSomething &rsSomething = sSomething;rsSomething.nValue = 5;// Member selection using pointer to structSomething *psSomething = &sSomething;(*psSomething).nValue = 5;


0 0
原创粉丝点击