随笔 - 60, 文章 - 0, 评论 - 197, 引用 - 0
数据加载中……

C++ 拷贝构造函数与赋值函数

C++的拷贝函数和赋值函数既有联系又有区别,不细究的话很容易搞混,遂以小例示之如下,权作解惑之用

// test.cpp
#include <iostream>
#include <stdlib.h>
#include <algorithm>
using namespace std;

class Book
{
public:
  Book(const char *name, const char*author, const double price): price(price) {
    this->name = new char[strlen(name)+1];
    this->author = new char[strlen(author)+1];

    strcpy(this->name, name);
    strcpy(this->author,author);
  }

  Book(const Book& book){
    name = new char[strlen(book.name)+1];
    author = new char[strlen(book.author)+1];

    price = book.price;
    strcpy(name, book.name);
    strcpy(author, book.author);
  }

  Book& operator=(const Book& rhs) {
    Book(rhs).swap(*this);           // 先创建临时对象Book(rhs), 再调用下面的swap进行数据交换,
                                                  // 注意与*this交换数据的是临时对象, rhs并未修改,只是swap
                                                  // 结束后临时对象拥有了*this的数据, 而*this也拥有了由rhs
                                                  // 构造的临时对象的数据, 临时对象生命期结束时,*this的数据
                                                  // 会被销毁。
    return *this;                             
  }

  ~Book(){
    delete[] name;
    delete[] author;
  }

private:
  Book& swap(Book& rhs) {
    double temp = rhs.price;
    rhs.price = price;
    price = temp;

    std::swap(name, rhs.name); // std::swap()只是简单的交换指针的值
    std::swap(author, rhs.author);
    return *this;
  }
 
public:
  char* name;
  char* author;
  double price;
};

int main() {
  Book a("The C++ standard library", "Nicolai M. Josuttis", 98);
  Book b = a; // 对象b不存在, 拷贝构造函数在这里被调用

  Book c("Emacs Lisp manual", "stallman", 0);
  c = a; // c对象已经存在, 赋值函数(operator=)在这里被调用

  cout << a.name << endl;
  cout << a.author << endl;
  cout << a.price << endl << endl;

  cout << b.name << endl;
  cout << b.author << endl;
  cout << b.price << endl << endl;

  cout << c.name << endl;
  cout << c.author << endl;
  cout << c.price << endl;
}

编译:
g++ -o test test.cpp

运行结果:
The C++ standard library
Nicolai M. Josuttis
98

The C++ standard library
Nicolai M. Josuttis
98

The C++ standard library
Nicolai M. Josuttis
98

 

posted on 2007-09-09 17:49 Normandy 阅读(2691) 评论(2)  编辑 收藏 引用 所属分类: Programming

评论

# re: C++ 拷贝构造函数与赋值函数  回复  更多评论   

写的不错吗?一个字:顶!
2007-09-17 10:32 | Kyle

# re: C++ 拷贝构造函数与赋值函数[未登录]  回复  更多评论   

挺好
2010-08-06 18:12 | zhupf

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理