c++-this指针

使用this可以用来表示当前类的变量

/*
string 字符串 
*/ 
#include <iostream>
#include <cstring>

using namespace std; 

class String {
public:
    String(const char* str) {
        m_str = new char[strlen(str)+1]; 
        strcpy(m_str, str); 
    }
    ~String(void) {
        cout << "析构函数" << endl; 
        delete m_str; 
    }
    //深拷贝 
    String(const String& that) {
        m_str = new char[strlen(that.m_str)+1]; 
        strcpy(m_str, that.m_str); 
    }
    void print(void) {
        cout << m_str << endl; 
    }
    const char* c_str(void) const {
        return m_str; 
    }

private:
    char* m_str; 

}; 

int main() {
    String s = "hello"; 
    cout << s.c_str() << endl; 
    String s1(s); 
    cout << s1.c_str() << endl; 
    

}

使用this进行自引用

/*
返回this进行自引用 
*/ 
#include <iostream>

using namespace std; 

class Counter {
public:
    Counter(int count = 0):m_count(count){} 
    void print(void) {
        cout << m_count << endl; 
    }
    Counter& add(void) {
        ++m_count; 
        return *this; 
    }
    void destory(void) {
        cout << "该类已经删除" << endl; 
        delete this; 
    }


private:
    int m_count; 
}; 


int main() {
    Counter c; 
    c.add().add().add(); 
    c.print(); 

    Counter *pc = new Counter; 
    pc->add(); 
    pc->print(); 
    cout << "pc" << pc << endl;
     pc->destory();  //delete pc; 

}

两个类进行相互的调用 ,这里使用老师帮助学生,学生问老师,老师解答

/*
两个类进行相互调用 
*/ 
#include <iostream>

using namespace std; 

class Student; 

class Teacher {
public:
    void eduate(Student s);
    void reply(void); 
};

class Student {
public:
    void ask(Teacher *t); 
};

void Teacher::eduate(Student that) {
    that.ask(this); 
}

void Student::ask(Teacher *t) {
    cout << "这里有多少个人" << endl; ; 
    t->reply(); 
}

void Teacher::reply(void) {
    cout << "这里有三个人" << endl; 

}

int main() {
    Teacher t; 
    Student s; 
    t.eduate(s); 
}

 

posted @ 2020-04-02 18:37  c语言我的最爱  阅读(310)  评论(0编辑  收藏  举报