As an experienced programmer, I must be familiar with the C ++ programming language. This language has become an important application language in the development field. Next, you can further understand the C ++ language based on the understanding of the C ++ assignment function in this article.
C ++'s copy function and C ++'s value assignment function have both links and differences. It is easy to confuse them without further research. The following is an example to illustrate how to use the function to solve the problem.
Example code of the C ++ assignment function:
- // 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); // create a temporary object Book (rhs) first ),
Call the following swap for data exchange,
- // Note that a temporary object is used to exchange data with * this. rhs is not modified, but swap
- // After the end, the temporary object has * this data, and * this also has
- // Construct the data of the temporary object. * this data is generated when the life cycle of the temporary object ends.
- // It will be destroyed.
- 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 () is just a simple exchange of pointer values
- Std: swap (author, rhs. author );
- Return * this;
- }
- Public:
- Char * name;
- Char * author;
- Double price;
- };
- Int main (){
- Book a ("The C ++ standard library", "niclai M. josutis", 98 );
- Book B = a; // object B does not exist. The copy constructor is called here.
- Book c ("Emacs Lisp manual", "stallman", 0 );
- C = a; // The c object already exists. The C ++ assignment function (operator =) is called here.
- Cout <a. name <endl;
- Cout <a. author <endl;
- Cout <a. price <endl;
- Cout <B. name <endl;
- Cout <B. author <endl;
- Cout <B. price <endl;
- Cout <c. name <endl;
- Cout <c. author <endl;
- Cout <c. price <endl;
- }
Compile:
- g++ -o test test.cpp
Running result:
- The C++ standard library
- Nicolai M. Josuttis
- 98
- The C++ standard library
- Nicolai M. Josuttis
- 98
- The C++ standard library
- Nicolai M. Josuttis
- 98
The above is an introduction to the C ++ assignment function.