您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)C++中有哪些賦值函數(shù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
C++賦值函數(shù)相關(guā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ì)被銷(xiāo)毀。
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)存在, 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
運(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
看完上述內(nèi)容,你們對(duì)C++中有哪些賦值函數(shù)有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。