一、this函数
对于普通的成员函数,this指向调用该函数的对象
对于构造函数,this指向正在创建的对象
#include <iostream> using namespace std; class Teacher{ public: /*Teacher(const string& name,int age) :m_name(name),m_age(age){ cout << "构造函数:" << this << endl; }*/ //通过this区分函数的形参和成员变量 Teacher(const string& m_name,int m_age){ this->m_name = m_name ; this->m_age = m_age; } void print(void){ cout << m_name << ',' << m_age <<endl; cout << this->m_name << ',' << this->m_age << endl; }/*编译处理后变成类似如下: void print(Teacher* this){ cout << this->m_name << ',' << this->m_age << endl; }*/ private: string m_name; int m_age; }; int main(void) { Teacher t1("杨健",45); cout << "&t1:" << &t1 << endl; Teacher t2("王建立",45); cout << "&t2:" << &t2 << endl; t1.print();//Teacher::print(&t1) t2.print();//Teacher::print(&t2) return 0; }
#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; //this指向调用对象 //*this就是调用对象 return *this;//返回自引用 } void destroy(void){ //... cout << "destroy:" << this << endl; delete this; } private: int m_count; }; int main(void) { Counter c; c.add().add().add(); c.print();//3 Counter* pc = new Counter; pc->add(); pc->print();//1 //delete pc; cout << "pc:" << pc << endl; pc->destroy(); return 0; }
#include <iostream> using namespace std; class Student; class Teacher{ public: void edudate(Student* s); void reply(const string& answer); private: string m_answer; }; class Student{ public: void ask(const string& question,Teacher* t); }; void Teacher::edudate(Student* s){ s->ask("什么是this指针?",this); cout << "学生回答:" << m_answer << endl; } void Teacher::reply(const string& answer){ m_answer = answer; } void Student::ask( const string & question,Teacher* t){ cout << "问题:" << question << endl; t->reply("不知道"); } int main(void) { Teacher t; Student s; t.edudate(&s); return 0; }
二、析构函数,主要负责清理对象生命周期中的动态资源,当对象被销毁时,该类的析构函数自动被调用和执行
#include <iostream> using namespace std; class Integer{ public: Integer(int i){ m_pi = new int; *m_pi = i; } ~Integer(void){ cout << "析构函数" << endl; delete m_pi; } void print(void) const { cout << *m_pi << endl; } private: int* m_pi; }; int main(void) { if(1){ Integer i(100); i.print();//100 cout << "test1" << endl; Integer* pi = new Integer(200); pi->print(); delete pi; cout << "test3" << endl; } cout << "test2" << endl; return 0; }
#include <iostream> using namespace std; class A{ public: A(void){ cout << "A(void)" << endl; } ~A(void){ cout << "~A(void)" << endl; } }; class B{ public: B(void){ cout << "B(void)" << endl; } ~B(void){ cout << "~B(void)" << endl; } A m_a; }; int main(void) { B b; return 0; }