选择运算符

来源:互联网 发布:肯德基 麦当劳 知乎 编辑:程序博客网 时间:2024/06/05 16:34

引用和指针

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

int nValue = 5;int *const pnValue = &nValue;int &rnValue = nValue;*pnValue and rnValue evaluate identically. As a result, the following two statements produce the same effect:*pnValue = 6;rnValue = 6;

同样,一个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 = &sSo

注意指针解引用必须括在括号因为成员选择运算符具有比解引用操作符的优先级更高的

因为访问结构和类成员通过指针是笨拙的语法,C + +提供的第二个成员选择运算符(->)从指针做成员选择。下面的两行是等价的


0 0