条款30:避免写出member function,传回一个non-const function或reference并指向private或protect成员

1,先看一个例子:
class Address { ... };           // where someone lives

class Person
{
public:
  Address& personAddress() { return address; }
private:
  Address address;
};

Person scott();            
Address& addr = scott.personAddress(); //addr看作一个全局对象
这个时候addr乘了scott.address的另一个名称,可以通过addr任意读写address.
因此,scott.addres不再是private,变成了public.

2,相同的道理,适用于指针成员.
例如:
class Person
{
public:
  Address * personAddress() { return &address; }
private:
  Address address;
};

Address *addrPtr = scott.personAddress();  // same problem as above
改写*addrPtr,即可改变address的值.

3,也适用于成员函数.
如:
class Person;                   // forward declaration
typedef void (Person::*PPMF)();

class Person
{
public:
static PPMF verificationFunction()
{
return &Person::verifyAddress;
}

private:
Address address;
void verifyAddress();
};

下面这个动作:
PPMF pmf = scott.verificationFunction();
(scott.*pmf)(); //等同于调用scott.verificationFunction.

你可能感兴趣的:(reference)