勿在浮沙筑高台--P7-P9

2021-01-29  本文已影响0人  Catherin_gao

总:Classes的两个经典分类

一. string class

#ifndef  __MYSTRING__             string.h
#define __MYSTRING__

class String
{
...
};

String::function(...) ...
Global::function(...) ...

#endif
int main(){
  String s1();
  String s2("hello");

  String s3(s1);
  cout << s3 << endl;
  s3 = s2;
  cout << s3 <<endl;
}

二. Big Three, 三个特殊函数

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

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

inline 
String::String(const char* cstr = 0){
    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;
}
{
   String s1();
   String s2("hello");

   String* p = new String("hello");
   delete p;
}

四. 必须有拷贝构造和拷贝赋值函数

五. 拷贝构造函数

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

{
    String s1("hello");
    String s2(s1);
 // String s2 = s1;
}

六. 拷贝赋值函数

inline
String& String::opeator=(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;
}

七. output函数

#include<iostream.h>
ostream operator<<(ostream& os, const String& str){
    os<< str.get_c_str();
    return os;
}

{
    String s1("hello");
    cout << s1;
}

八. stack 栈,heap堆

class Complex{...};
...
{
    Complex c1(1, 2);
    Complex* p = new Complex(3);
}

九. objects的生命期

class Complex{...};
...
{
   Complex c1(1, 2);
}
class Complex{...};
...
{
   static Complex c2(1, 2);
}
class Complex {...};
...
Complex c3(1, 2);

int main(){
 ...
}
class Complex {...};
...
{
    Complex* p = new Complex;
    ....
    delete p;
}
class Complex {...};
...
{
    Complex* p = new Complex;
}

十. new: 先分配memory,再调用构造函数

Complex *pc;

void* mem = operator new( sizeof(Complex) ); //分配内存
pc = static_cast<Complex*>(mem);                   //转型
pc->Complex::Complex(1, 2);                             //构造函数
// Complex::Complex(pc, 1, 2); 

十一. 先调用析构函数,再释放memory

delete ps;

String::~String(ps);      //析构函数
operator delete(ps);     //释放内存, 内部调用free(ps)
上一篇下一篇

猜你喜欢

热点阅读