加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++中的三大函数和操作符重载(Boolan)

发布时间:2020-12-16 05:13:37 所属栏目:百科 来源:网络整理
导读:C++中三大函数: 析构函数 复制构造函数 =操作符(copy assignment operator) 这三个特殊的成员函数如果程序员没有实现,编译器将提供默认的实现方式。 析构函数: 形如~foo_t(),函数名和构造函数相同,前面加~,如果对象是自由变量创建,析构函数将在脱离

C++中三大函数:

  • 析构函数
  • 复制构造函数
  • =操作符(copy assignment operator)

这三个特殊的成员函数如果程序员没有实现,编译器将提供默认的实现方式。

析构函数:

形如~foo_t(),函数名和构造函数相同,前面加~,如果对象是自由变量创建,析构函数将在脱离作用域时调用。如果对象是通过new操作符创建的,则通过delete操作符调用析构函数。

复制构造函数:

形如foo_t(const foo_t& foo),以下情况复制构造函数均会被调用:

  1. 当对象按值返回时候(returned by value)
  2. 调用按值传参的函数(passed by value)
  3. 通过thrown抛出或caught捕获的对象
  4. 对象处于()包围的初始化列表中

=操作符:

重载=操作符,如foo_t& operator=(const foo_t& foo),对已有对象的赋值操作将调用该函数(未初始化的对象成员将调用复制构造函数)。

以下为代码实例:

#include <cstring>
#include <iostream>
class foo_t {
 friend std::ostream &operator<<(std::ostream &os,foo_t const &foo) {
  os << foo.data;
  return os;
 }
 public:
 foo_t(void) : data(new char[14]) { std::strcpy(data,"Hello,World!"); }
 ~foo_t(void) { delete[] data; }
 foo_t(const foo_t& other);
 foo_t &operator=(const foo_t& other);
 private:
 char *data;
};
foo_t::foo_t(const foo_t& other) {
 std::cout << "call copy constructor!!!" << std::endl;
 this->data = new char[strlen(other.data) + 1];
 strcpy(this->data,other.data);
}
foo_t& foo_t::operator=(const foo_t& other) {
 std::cout << "call the copy assignment operator!!!" << std::endl;
 if (this == &other)
   return *this;
 this->data = new char[strlen(other.data) + 1];
 strcpy(this->data,other.data);
 return *this;
}
int main() {
 foo_t foo;
 std::cout << foo << 'n';
 foo_t t(foo);
 // foo_t t2 = t;
 foo_t t3;
 t3 = t;
 return 0;
}

为了方便测试,可以分别在析构函数、拷贝构造、=重载处设置断点,观察程序执行流程。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程小技巧!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读