Use this variable can be used to represent the current class
/* 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; }
Use this self-reference
/* 返回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; }
Call each other two classes, where teachers use to help students, the students asked the teacher, the teacher answers
/ * Two call each other classes * / #include <the iostream> the 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 ( the this ); } void Student :: ASK (Teacher * T) { COUT << " there are number of individuals " << endl; ; t->reply(); } void Teacher::reply(void) { cout << "这里有三个人" << endl; } int main() { Teacher t; Student s; t.eduate(s); }