新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C++賦值函數(shù)代碼詳解
作為一個經(jīng)驗豐富的編程人員,想必對C++編程語言一定有所了解。因為這一語言已經(jīng)成為開發(fā)領(lǐng)域中一個重要的應(yīng)用語言。下面大家可以根據(jù)本文對C++賦值函數(shù)的理解,進一步加深對C++語言的了解程度。

創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供吳堡網(wǎng)站建設(shè)、吳堡做網(wǎng)站、吳堡網(wǎng)站設(shè)計、吳堡網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、吳堡企業(yè)網(wǎng)站模板建站服務(wù),十載吳堡做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
C++的拷貝函數(shù)和C++賦值函數(shù)既有聯(lián)系又有區(qū)別,不細究的話很容易搞混,遂以小例示之如下,權(quán)作解惑之用。
C++賦值函數(shù)相關(guān)代碼示例:
- // test.cpp
- #include
- #include
- #include
- 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)建臨時對象Book(rhs),
再調(diào)用下面的swap進行數(shù)據(jù)交換,- // 注意與*this交換數(shù)據(jù)的是臨時對象, rhs并未修改,只是swap
- // 結(jié)束后臨時對象擁有了*this的數(shù)據(jù), 而*this也擁有了由rhs
- // 構(gòu)造的臨時對象的數(shù)據(jù), 臨時對象生命期結(jié)束時,*this的數(shù)據(jù)
- // 會被銷毀。
- 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不存在, 拷貝構(gòu)造函數(shù)在這里被調(diào)用
- Book c("Emacs Lisp manual", "stallman", 0);
- c = a; // c對象已經(jīng)存在, C++賦值函數(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
運行結(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
以上就是對C++賦值函數(shù)的相關(guān)介紹。
分享文章:C++賦值函數(shù)代碼詳解
本文來源:http://m.fisionsoft.com.cn/article/cooepjd.html


咨詢
建站咨詢
