effectiveC++(十六)(四)

2010-12-26 23:19:42 · 作者: · 浏览: 4638
;  // d2.x = 1, d2.y = 1

  d1 = d2;         // d1.x = 0, d1.y = 1!
}

请注意d1的base部分没有被赋值操作改变。

解决这个问题最显然的办法是在derived::operator=中对x赋值。但这不合法,因为x是base的私有成员。所以必须在derived的赋值运算符里显式地对derived的base部分赋值。

也就是这么做:

// 正确的赋值运算符
derived& derived::operator=(const derived& rhs)
{
  if (this == &rhs) return *this;

  base::operator=(rhs);    // 调用this->base::operator=
  y = rhs.y;

  return *this;
}

这里只是显式地调用了base::operator=,这个调用和一般情况下的在成员函数中调用另外的成员函数一样,以*this作为它的隐式左值。base::operator=将针对*this的base部分执行它所有该做的工作——正如你所想得到的那种效果。

但如果基类赋值运算符是编译器生成的,有些编译器会拒绝这种对于基类赋值运算符的调用(见条款45)。为了适应这种编译器,必须这样实现derived::operator=:

derived& derived::operator=(const derived& rhs)
{
  if (this == &rhs) return *this;

  static_cast<base&>(*this) = rhs;      // 对*this的base部分
                       &nb