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