作為一個經驗豐富的編程人員,想必對C++編程語言一定有所了解。因為這一語言已經成為開發領域中一個重要的應用語言。下面大家可以根據本文對C++賦值函數的理解,進一步加深對C++語言的了解程度。
C++的拷貝函數和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對象已經存在, 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
以上就是對C++賦值函數的相關介紹。