资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

C++中有哪些赋值函数

今天就跟大家聊聊有关C++中有哪些赋值函数,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

为本溪等地区用户提供了全套网页设计制作服务,及本溪网站建设行业解决方案。主营业务为网站设计制作、成都网站建设、本溪网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

C++赋值函数相关代码示例:

  1. // test.cpp  

  2. #include  

  3. #include  

  4. #include  

  5. using namespace std;  

  6. class Book  

  7. {  

  8. public:  

  9. Book(const char *name, const char*author, const double price): 
    price(price) {  

  10. this->name = new char[strlen(name)+1];  

  11. this->author = new char[strlen(author)+1];  

  12. strcpy(this->name, name);  

  13. strcpy(this->author,author);  

  14. }  

  15. Book(const Book& book){  

  16. name = new char[strlen(book.name)+1];  

  17. author = new char[strlen(book.author)+1];  

  18. price = book.price;  

  19. strcpy(name, book.name);  

  20. strcpy(author, book.author);  

  1. Book& operator=(const Book& rhs) {  

  2. Book(rhs).swap(*this); // 先创建临时对象Book(rhs), 
    再调用下面的swap进行数据交换,  

  3. // 注意与*this交换数据的是临时对象, rhs并未修改,只是swap  

  4. // 结束后临时对象拥有了*this的数据, 而*this也拥有了由rhs  

  5. // 构造的临时对象的数据, 临时对象生命期结束时,*this的数据  

  6. // 会被销毁。  

  7. return *this;   

  8. }  

  9. ~Book(){  

  10. delete[] name;  

  11. delete[] author;  

  12. }  

  13. private:  

  14. Book& swap(Book& rhs) {  

  15. double temp = rhs.price;  

  16. rhs.price = price;  

  17. price = temp;  

  18. std::swap(name, rhs.name); 
    // std::swap()只是简单的交换指针的值  

  19. std::swap(author, rhs.author);  

  20. return *this;  

  21. }  

  22. public:  

  23. char* name;  

  24. char* author;  

  25. double price;  

  26. };  

  27. int main() {  

  28. Book a("The C++ standard library", "Nicolai M. Josuttis", 98);  

  29. Book b = a; // 对象b不存在, 拷贝构造函数在这里被调用  

  30. Book c("Emacs Lisp manual", "stallman", 0);  

  31. c = a; // c对象已经存在, C++赋值函数(operator=)在这里被调用  

  32. cout << a.name << endl;  

  33. cout << a.author << endl;  

  34. cout << a.price << endl << endl;  

  35. cout << b.name << endl;  

  36. cout << b.author << endl;  

  37. cout << b.price << endl << endl;  

  38. cout << c.name << endl;  

  39. cout << c.author << endl;  

  40. 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++中有哪些赋值函数有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


新闻名称:C++中有哪些赋值函数
分享地址:http://cdkjz.cn/article/geospj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220