(3)基于对象 —class with pointer members — String

相关知识点

Big Three,三个特殊的函数

  • 拷贝构造函数
  • 拷贝赋值函数
  • 析构函数

一个class中如果含有指针,就应该自定义实现上面三个函数。

class with pointer members 必须有 copy ctorcopy op=函数,以实现用户自定义的深拷贝,而不是按编译器默认的浅拷贝。

{
    String s1("Hello World"); // 调用构造函数
    String s2(s1); // 调用拷贝构造函数
    String s3 = s1; // 调用拷贝构造函数,而不是拷贝赋值函数,因为 s3 是
                    // 新创建出来的,所以调用拷贝构造函数,和 s2(s1) 意思完全相同,只是符号不一样
}

ctor 和 dtor (构造函数 和 析构函数)

copy ctor (拷贝构造函数)

copy assignment operator (拷贝赋值函数)

所谓stack (栈), 所谓 heap (堆)

Stack,是存在于某作用域 (scope) 的一块內存空间 (memory space)。例如当你调用函數,函数本身即会形成一個 stack 用來放置它所接收的参数,以及返回地址。 在函数本体 (function body) 內声明的任何变量, 其所使用的內存块都取自上述 stack。

Heap,或叫system heap,是指由操作系統提供的 一块 global 內存空間,程序可動態分配 (dynamic allocated) 从其中去取得若干塊 (blocks)。

stack objects 的生命期:  其生命在作用域 (scope) 結束之后結束

static local objects 的生命期:其生命在作用域 (scope) 結束之後后然存在,直到整个程序結束

global objects 的生命期: 其生命在整个程序結束之后 才結束。你也可以把视为一种static object,其作用域 是「整个程序」

new:先分配 memory,再调用 ctor。

 构造函数全名: Complex::Complex(pc,1,2) 谁调用这个函数 谁就是this

delete:先调用 dtor,再释放 memory

array new 一定要搭配 array delete,不然容易造成内存泄露:

String

#ifndef __MYSTRING__
#define __MYSTRING__

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;
};

#include <cstring>

inline
String::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';
   }
}

inline
String::~String()
{
   delete[] m_data;
}

inline
String& 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;
}

inline
String::String(const String& str)
{
   m_data = new char[ strlen(str.m_data) + 1 ];
   strcpy(m_data, str.m_data);
}

#include <iostream>
using namespace std;

ostream& operator<<(ostream& os, const String& str)
{
   os << str.get_c_str();
   return os;
}

#endif
#include "string.h"
#include <iostream>

using namespace std;

int main()
{
  String s1("hello"); 
  String s2("world");
    
  String s3(s2);
  cout << s3 << endl;
  
  s3 = s1;
  cout << s3 << endl;     
  cout << s2 << endl;  
  cout << s1 << endl;      
}

猜你喜欢

转载自blog.csdn.net/qq_34863439/article/details/89036032