C++的拷貝函數(shù)和賦值函數(shù)既有聯(lián)系又有區(qū)別,不細(xì)究的話很容易搞混,遂以小例示之如下,權(quán)作解惑之用
// 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); // 先創(chuàng)建臨時(shí)對(duì)象Book(rhs), 再調(diào)用下面的swap進(jìn)行數(shù)據(jù)交換,
// 注意與*this交換數(shù)據(jù)的是臨時(shí)對(duì)象, rhs并未修改,只是swap
// 結(jié)束后臨時(shí)對(duì)象擁有了*this的數(shù)據(jù), 而*this也擁有了由rhs
// 構(gòu)造的臨時(shí)對(duì)象的數(shù)據(jù), 臨時(shí)對(duì)象生命期結(jié)束時(shí),*this的數(shù)據(jù)
// 會(huì)被銷毀。
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()只是簡(jiǎn)單的交換指針的值
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; // 對(duì)象b不存在, 拷貝構(gòu)造函數(shù)在這里被調(diào)用
Book c("Emacs Lisp manual", "stallman", 0);
c = a; // c對(duì)象已經(jīng)存在, 賦值函數(shù)(operator=)在這里被調(diào)用
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
運(yùn)行結(jié)果:
The C++ standard library
Nicolai M. Josuttis
98
The C++ standard library
Nicolai M. Josuttis
98
The C++ standard library
Nicolai M. Josuttis
98