赋值函数、拷贝构造函数

最经学习c++,发现很多高深的东西,发表出来于给位分享一下

#include <iostream>
#include <stdlib.h>
#include <algorithm>
using namespace std;
class Book
{
public:
    char* name;
    char* author;
    double price;
    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;
    }    
};
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值