极客班 C++(上)第二周学习笔记

来源:互联网 发布:asp.net mvc 获取域名 编辑:程序博客网 时间:2024/05/21 11:13

极客班 C++(上)第二周学习笔记

今天在网站首页上看到一句话“程序员之所以犯错误,不是因为他们不懂,而是因为他们自以为什么都懂。”私觉很有道理,但在自己与他人对问题出现分歧时,还是愿坚持第一先相信自己。

这两周课程主要讲了类创建方面需要注意的东西。
第一周讲的是class without pointer member ,
第二周讲的是class with pointer member .

class without pointer member
编译器会自动生成构造函数(className())、拷贝构造函数(className(const className&))、operator =(className operator=(const className&)),并且是正确可用的,当然此处自动生成的构造函数是无参构造函数,并且不执行实际操作,编程过程中还是应该按要求写构造函数。由于没有指针成员变量,也不需要写析构函数(~className)。
class complex{public:  complex (double r = 0, double i = 0)  : re (r), im (i) { }  complex& operator += (const complex&);  double real () const { return re; }  double imag () const { return im; }private:  double re, im;  friend complex& __doapl (complex *, const complex&);};inline complex&__doapl (complex* ths, const complex& r){  ths->re += r.re;  ths->im += r.im;  return *ths;}inline complex&complex::operator += (const complex& r){  return __doapl (this, r);}

小注: 重载 operator+= 时,返回类型处一定要写complex& ,原因同operator() 的重载。

class with pointer member
编译器依旧会自动生成构造函数、拷贝构造函数、operator =,但是由于class 中有指针成员变量,进行拷贝、=操作时只是进行了浅拷贝,即两个class 中的指针指向同一个地址。并且在delete时不能自动delete指针变量指向的区域,故需要写析构函数。
即对于这种class 定义时必需要写big three(拷贝构造、operator =、析构函数)。在构造函数中对于指针成员变量要分配空间(new);写析构函数对指针成员变量指向的内存进行释放;做拷贝时,也要对指针成员变量进行特殊操作(有需要时进行内存的释放和重新分配)。
注:operator = 中需要判断两个class 实例是否是同一个,判断是否需要执行拷贝,避免self assignment。例子如下:
if(this = &classname) return*this;
class String{public:                                    String(const char* cstr=0);                        String(const String& str);                       String& operator=(const String& str);            ~String();                                       char* get_c_str() const { return m_data; }private:   char* m_data;};inlineString::String(const char* cstr){   if (cstr) {      m_data = new char[strlen(cstr)+1];      strcpy(m_data, cstr);   }   else {         m_data = new char[1];      *m_data = '\0';   }}inlineString::~String(){   delete[] m_data;}inlineString& String::operator=(const String& str){   if (this == &str)      return *this;   delete[] m_data;   m_data = new char[ strlen(str.m_data) + 1 ];   strcpy(m_data, str.m_data);   return *this;}inlineString::String(const String& str){   m_data = new char[ strlen(str.m_data) + 1 ];   strcpy(m_data, str.m_data);}

注:本篇中className表示类名,classname表示类实例

1 0
原创粉丝点击