ITeye博客

条款16: 在operator=中对所有数据成员赋值

lin_style · 2008-02-01 18:08 · C/C++ · 编程语言 · Java · Markdown

条款16: 在operator=中对所有数据成员赋值

class base {
public:
  base(int initialvalue = 0): x(initialvalue) {}
  virtual  void print();
private:
  int x;
};

void base::print()
{
     cout<<"base: x = "<<x<<endl;
}

class derived: public base {
public:
  derived(int initialvalue)
  : base(initialvalue), y(initialvalue) {}

  void print();
  derived& operator=(const derived& rhs);

private:
  int y;
};

void derived::print()
{
     cout<<"derived: y = "<<y<<endl;
}

derived& derived::operator=(const derived& rhs)
{
         if(this==&rhs)
                  return *this;
         //base::operator=(rhs);
         y = rhs.y;
         
         return *this;
}

int main()
{
    base b1;
    derived d1(10);
    derived d2(20);
    d1=d2;
    d1.print();
    b1 = (base)d1;
    b1.print();
    
    system("pause");
    return 0; 
}

输出: derived: y = 20 base: x = 10 请按任意键继续. . .

这里讲了一个漏赋值的情况。在derived& derived::operator=里加入吗?别忘了x是私有的,为基类加个

赋值函数?不对,这可以巧妙的运用一个默认的赋值函数。base::operator=(rhs);你不用担心rhs是派生

的对象,在拷贝时会发生问题。在C++的继承上有固定的内存布局,可以无需担心。你可以想像到的编码

为 x=rhs.x;

但是如果说这个赋值运算符是编译器生成的,有写编译器会拒绝对于这种的调用,可以手工试试 static_cast<base&>(*this)=rhs;这样会导致拷贝构造函数的调用。 这代码比较怪异,但要注意这个只是把他引用给转换了,而不是把整个对象进行转换。如果是转换一个对

象那必然要重新生成一个对象。 那么至此我们可以总结出,在对派生类进行赋值时,要注意对基类成员的赋值,接着对本身赋值 但我对它还不是很满意,因为他似乎没有表现出一种连带关系,放的位置不合适 最简洁的方法我还是喜欢放在派声类的拷贝函数中 例: derived(const derived& rhs):base(rhs),y(rhs.y){}

评论(1)

  1. #1 楼 · lin_style · 2008-02-01 18:08

    为什么编辑器里code 只有java...

评论功能维护中,当前仅展示历史评论。