本文主要是介绍完整的类(无参构造函数,有参构造函数,拷贝构造函数,赋值运算符重载,析构函数),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
之所以又发一遍,是因为前面好像写的有问题(其实有没有我也忘了,记得好像是有点小问题),至于原因嘛,就是是懒.(毕竟我只是为了从头再走一遍做下笔记而已)
但是我怕万一有小伙伴看到了产生误导就不好了,误人子弟的事做了亏心啊.所以就把它单独拿出来发了一下.
#define _CRT_SECURE_NO_WARNINGS#include <iostream>using namespace std;class Student
{
public://无参构造函数Student(){this->m_name = new char[1];*this->m_name = 0;}//有参构造函数Student(const char* name){m_name = new char[strlen(name) + 1];strcpy(m_name, name);}//拷贝构造函数Student(const Student& s){m_name = new char[strlen(s.m_name) + 1];strcpy(m_name, s.m_name);}//赋值运算符重载(反正我一直叫它赋值构造函数)Student& operator=(const Student& s){//因为需要释放原空间,如果不做此判断,会赋值释放的空间(值不确定)if (m_name == s.m_name){return *this;}if (this->m_name != nullptr){delete[]this->m_name;this->m_name = nullptr;}this->m_name = new char[strlen(s.m_name) + 1];strcpy(this->m_name, s.m_name);return *this;}//析构函数~Student(){if (this->m_name != nullptr){delete[]this->m_name;this->m_name = nullptr;}}void studentShow()const{cout << this->m_name << endl;}private:char* m_name;
};int main()
{//调用有参构造Student s = "hello world";//调用无参构造函数Student s2;//调用复制构造函数Student s3(s2);//调用赋值构造函数s2 = s3 = s;s.studentShow();s2.studentShow();s3.studentShow();return 0;
}
输出
hello world
hello world
hello world
这篇关于完整的类(无参构造函数,有参构造函数,拷贝构造函数,赋值运算符重载,析构函数)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!